使用触发器回滚更新

时间:2014-02-18 20:47:29

标签: sql-server

我正在尝试创建一个触发器,根据字段中是否存在值来回滚更新或删除。 触发器是:

CREATE TRIGGER [dbo].[tr_CheckValidation_Observation]
ON [dbo].[tbl_observation]
AFTER UPDATE, DELETE
AS
IF EXISTS (SELECT *
        FROM deleted as d
        WHERE d.verificationDate IS NOT NULL)

BEGIN
RAISERROR ('Cannot change data that has been validated', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;

GO

目前,所有记录的verfifiedDate都为空

如果我这样做:

IF EXISTS (select * from tbl_observation
            where verificationDate is not null)
    BEGIN
        print 'Verification Date has values'
    END
ELSE
    BEGIN
        print 'Verification Date has no values'
        update tbl_observation set verificationDate = GETDATE() where water_year = 2002
    END

我明白了:

  

验证日期没有值   消息50000,级别16,状态1,过程tr_CheckValidation_Observation,第12行无法更改数据   已经过验证的消息3609,级别16,状态1,过程   tr_Modified_Observation,第6行事务在触发器中结束。   批次已中止。

我是否错误地使用了已删除的表格,还是有其他方法来锁定单个行?

谢谢!

0 个答案:

没有答案