我正在使用一个数据库,该数据库有一个触发器,可以通过引发错误而不提交删除来防止删除某个表中的记录。如果要删除的记录列具有特定值,我需要修改行为以允许删除。
以下是当前代码:
CREATE TRIGGER [dbo].[MyTable_PreventDelete]
ON [dbo].[MyTable]
INSTEAD OF DELETE
AS
-- TODO: Only run the code below if Deleted = 0
ROLLBACK
RAISERROR('ERROR: That column may not be deleted.',16,1)
RETURN
GO
我试图简单地将错误调用包装在条件中,但似乎我不能直接引用受影响行的列:
...
CREATE TRIGGER [dbo].[MyTable_PreventDelete]
ON [dbo].[MyTable]
INSTEAD OF DELETE
AS
IF IsDeleted = 0
BEGIN
ROLLBACK
RAISERROR('ERROR: That column may not be deleted.',16,1)
RETURN
END
GO
答案 0 :(得分:1)
经过更多调查,这是做了什么。这些操作的每个触发器中都引用了3个临时表(INSERTED,UPDATED,DELETED)。在这种情况下,我们将检查DELETED中受影响的记录(反映批次中受影响的记录)。如果没有设置标志,则会引发错误:
IF EXISTS(SELECT 1 FROM DELETED d WHERE d.Deleted=0)
BEGIN
ROLLBACK
-- the rollback is unnecessary
RAISERROR('ERROR: That column may not be deleted.',16,1)
END
ELSE
BEGIN
DELETE c
FROM [dbo].[MyTable] c
INNER JOIN DELETED d
ON c.PrimaryKey = d.PrimaryKey
END