1

我正在使用一个具有触发器的数据库,该触发器通过引发错误而不提交删除来防止删除某个表中的记录。如果要删除的记录的列具有特定值,我需要修改行为以允许删除。

这是当前代码:

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
4

1 回答 1

1

After more investigation, here's what was done. There are 3 temp tables (INSERTED, UPDATED, DELETED) referenced in each trigger for those actions. In this case, we'll check the records affected in the DELETED (which reflect the records to be affected in the batch). If any does not have the flag set, the error is raised:

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
于 2013-06-12T14:00:40.597 回答