防止删除特定记录

时间:2010-10-27 20:09:39

标签: sql-server triggers sql-server-2008-r2

我想阻止删除特定记录。此触发器适用于该特定记录。但是,其他记录在被删除时仍然存在。为什么呢?

 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

如何确保按预期删除与上述条件不匹配的行?

2 个答案:

答案 0 :(得分:4)

你有一个INSTEAD OF触发器,所以你需要一个实际的DELETE。

我还考虑过滤掉受保护的行,因为:

  • 你需要抛出错误吗?还是默默地忽略?
  • 包含受保护行的多行删除怎么样:中止整个,或删除其余行?

类似的东西:

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

答案 1 :(得分:3)

因为这是INSTEAD OF,你仍然需要对默认情况执行删除操作。