简体   繁体   English

使用 SQL 服务器更新触发器

[英]Update trigger with SQL Server

With these two tables:有了这两张表:

Table A:表 A:

 key integer
 field varchar

Table B表 B

oldkey integer
oldfield varchar
newkey integer
newfield varchar

I want to archive all operations on A in B.我想将 A 上的所有操作归档到 B 中。

It is easy to do for INSERT or DELETE statements, but how to do that with UPDATE ones?对于 INSERT 或 DELETE 语句很容易做到这一点,但如何用 UPDATE 语句做到这一点? Especially for multiple rows UPDATE statements, of course...特别是对于多行 UPDATE 语句,当然......

Here is my actual trigger:这是我的实际触发器:

create trigger mytrigger 
on TableA
after insert, update, delete
as
begin
    declare @wAction char(1);

    set @wAction = (case 
                       when exists (select 1 from INSERTED)
                            and exists (select 1 from DELETED)   
                          then 'U'
                       when exists (select 1 from INSERTED)  
                          then 'I'
                       when exists (select 1 from DELETED)   
                          then 'X'
                       else ''
                    end);

    if (@wAction = 'I') 
    begin
        insert into TableB 
            select null, null, key, field 
            from inserted;    
    end
    else if (@wAction = 'X') 
    begin
        insert into TableB 
            select key, field, null, null 
            from deleted;    
    end
    else if (@wAction = 'U') 
    begin
        --    BUT WHAT TO DO THERE ?
    end
end

I read there that using cursors in triggers is not recommended, but I have no other idea...我在那里读到不建议在触发器中使用游标,但我没有其他想法......

Thanks for any help !谢谢你的帮助 !

How about this:这个怎么样:

else if (@wAction = 'U') 
begin
    insert into TableB (oldkey, oldvalue, newkey, newvalue)
        select d.key, d.field, i.key, i.field
        from deleted d
        inner join inserted i on d.key = i.key;
end

This assumes the key is the primary key and doesn't change.假设key是主键并且不会改变。 If that's not the case - then you need to join Inserted (new values after update) and Deleted (old values before update) on whatever other primary key column you have that is stable and doesn't change during an UPDATE ...如果不是这种情况 - 那么您需要在您拥有的任何其他稳定且在UPDATE期间不会更改的主键列上加入Inserted (更新后的新值)和Deleted (更新前的旧值)......

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

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