문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top