簡體   English   中英

使用 SQL 服務器更新觸發器

[英]Update trigger with SQL Server

有了這兩張表:

表 A:

 key integer
 field varchar

表 B

oldkey integer
oldfield varchar
newkey integer
newfield varchar

我想將 A 上的所有操作歸檔到 B 中。

對於 INSERT 或 DELETE 語句很容易做到這一點,但如何用 UPDATE 語句做到這一點? 特別是對於多行 UPDATE 語句,當然......

這是我的實際觸發器:

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

我在那里讀到不建議在觸發器中使用游標,但我沒有其他想法......

謝謝你的幫助 !

這個怎么樣:

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

假設key是主鍵並且不會改變。 如果不是這種情況 - 那么您需要在您擁有的任何其他穩定且在UPDATE期間不會更改的主鍵列上加入Inserted (更新后的新值)和Deleted (更新前的舊值)......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM