用于检查先前值的SQL触发器

时间:2016-07-20 09:22:16

标签: sql sql-server database-trigger

我在表tblA上有一个触发器,如果​​状态为closed,它会向表tblB插入一条记录。下面的代码工作正常,但我希望它只在以前的状态不是closed时执行。我怎么检查呢?

ON tblA
AFTER UPDATE
AS
  BEGIN
    SET NOCOUNT ON
    INSERT INTO tblB 
        (a_id, action, usr)
        select a.ID, 'closed', a.usr
        from tblA a
    WHERE a.Status LIKE 'closed';  
    END

1 个答案:

答案 0 :(得分:4)

如果SQL Server中的触发器无法访问inserteddeleted(或两者),则始终会怀疑它,因为这些是伪表,可以为您提供的详细信息改变

你想要这样的东西:

INSERT INTO tblB 
    (a_id, action, usr)
    select a.ID, 'closed', a.usr
    from inserted a
            inner join
         deleted d
            on a.ID = d.ID
WHERE a.Status = 'closed'
  AND d.Status != 'closed';