简体   繁体   中英

Update trigger with SQL Server

With these two tables:

Table A:

 key integer
 field varchar

Table B

oldkey integer
oldfield varchar
newkey integer
newfield varchar

I want to archive all operations on A in B.

It is easy to do for INSERT or DELETE statements, but how to do that with UPDATE ones? Especially for multiple rows UPDATE statements, of course...

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. 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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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