简体   繁体   English

日志触发器(更新前)-SQL Server

[英]Log Trigger (BEFORE UPDATE) - SQL Server

I have a table: 我有一张桌子:

TABLE1 : TABLE1

cod   |           date
 1    |  2008-07-03 00:00:00.000
 2    |  2009-09-03 00:00:00.000
 5    |  2010-12-03 00:00:00.000

And I have a trigger: 我有一个触发器:

CREATE TRIGGER trigger1
ON TABLE1
INSTEAD OF UPDATE
AS
    DECLARE
        @cod   numeric(9)
       ,@date  datetime

    DECLARE c_test cursor for select cod, data from TABLE1

    open c_test 
    fetch next from c_test into @cod, @date

    WHILE @@FETCH_STATUS = 0 
        BEGIN

           IF(@date < GETDATE())
           BEGIN
                INSERT INTO TABLE_AUDIT (cod, date, date_alt) VALUES (@cod, @date, GETDATE());
           END
           fetch next from c_test into @cod, @date
        END

    close c_test
    deallocate c_test

I want to execute an update like this: 我要执行这样的更新:

update TABLE1 
set date = '2003-07-15 00:00:00.000' 
where cod = 5;

and I want the old value from TABLE1 (before the update, value 2010-12-03 00:00:00.000) inserted into TABLE_AUDIT and after TABLE1 receives the new value 2003-07-15 00:00:00.000 from the above update. 我想将TABLE1的旧值(更新之前,值2010-12-03 00:00:00.000)插入TABLE_AUDIT并且TABLE1从上述更新中收到新值2003-07-15 00:00:00.000之后,

I know SQL Server doesn't have BEFORE trigger, so it's because I'm asking any alternatives. 我知道SQL Server没有触发BEFORE ,这是因为我在问其他选择。

Thanks! 谢谢!

Instead of this performance killer INSTEAD OF TRIGGER with cursor, you can simply have an after trigger something like this .... 代替使用光标来INSTEAD OF TRIGGER这种性能的杀手INSTEAD OF TRIGGER ,您可以简单地使用After触发器,例如...。

CREATE TRIGGER trigger1
ON TABLE1
AFTER UPDATE
AS
BEGIN
   SET NOCOUNT ON;

   INSERT INTO TABLE_AUDIT (cod, [date], date_alt)
   SELECT cod, [date], GETDATE()
   FROM deleted 
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM