views:

36

answers:

2

I want to prevent a specific record from being deleted. This trigger works fine for that specific record. However, other records still remain when they're being deleted. Why?

 ALTER TRIGGER [Globalization].[CountriesTracker] 
 ON [Globalization].[Countries] 
 INSTEAD OF DELETE
 AS 
 BEGIN
SET NOCOUNT ON;
IF ((Select COUNT(*) from [Deleted]
     Where [Deleted].[CountryId] = '36bd1536-fb56-4ec4-957e-1b3afde16c56') = 1)
BEGIN       
    RAISERROR('You can not delete this specific record!', 0, 0)
    ROLLBACK TRANSACTION
    RETURN
END
END

How can I ensure that rows not matching the above condition are being deleted as expected?

+3  A: 

Because this is INSTEAD OF you still need to perform the delete operation for the default case.

jamietre
Oh, I recently started to using triggers and I'm not too familiar with that! ;)
Sadegh
+3  A: 

You have an INSTEAD OF trigger so you need an actual DELETE in it.

I'd also consider simply filtering the protected row out because:

  • Do you need an error throwing? Or silently ignore?
  • What about multi row deletes that contain the protected row: abort the whole, or delete the rest?

Something like:

ALTER TRIGGER [Globalization].[CountriesTracker]  ON [Globalization].[Countries] 
 INSTEAD OF DELETE
 AS 
SET NOCOUNT ON;

DELETE
   CT
FROM
   [Globalization].[Countries] C
   JOIN
   DELETED D ON C.CountryId = D.CountryId
WHERE
    [Deleted].[CountryId] <> '36bd1536-fb56-4ec4-957e-1b3afde16c56'
 GO
gbn