日志触发器(BEFORE UPDATE) - SQL Server

时间:2014-09-26 14:36:15

标签: sql sql-server triggers

我有一张桌子:

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

我有一个触发器:

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

我想执行这样的更新:

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

我希望将TABLE1(更新前的值,2010-12-03 00:00:00.000)中的旧值插入TABLE_AUDIT并在TABLE1之后收到新值2003-07-15 00:00:00.000来自上述更新。

我知道SQL Server没有BEFORE触发器,所以这是因为我要求任何替代方案。

谢谢!

1 个答案:

答案 0 :(得分:4)

使用光标代替这个性能杀手INSTEAD OF TRIGGER,你可以简单地使用这样的后触发器....

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