觸發器實現多表之間的增加、刪除及更新


注:本文參考http://blog.sina.com.cn/s/blog_a0912d340101gxhb.html

常見的觸發器有三種:分別應用於Insert,Update,Delete事件。

1.數據同步增加

如有兩張表:A表和B表,創建觸發器使當A表插入數據后B表也同步插入數據。其中B表插入數據的字段需要同A表中的字段相對應。

1 create trigger 觸發器名稱 2 on A表 3 after insert
4 as 
5 begin insert into B表(B表字段1,B表字段2,B表字段3) 6 select A表字段1,A表字段2,A表字段3 7 from inserted 8 end

實例測試:

實現若Info_Stu有新的數據插入,則將數據的Name提取出,同步到Info_Borrow表

1 create trigger triCopy_Stu2Borrow 2 on Info_Stu 3 after insert
4 as 
5 begin insert into Info_Borrow(Name) 6 select Name from Info_Stu 7 end

測試效果如下:

 

2.數據同步刪除

如有兩張表:A表和B表,創建觸發器使當A表刪除數據后B表也能同步刪除數據。其中B表與A表應有相應主鍵關聯。

1 create trigger 觸發器名稱 2 on A表 3 after delete
4 as begin delete B表 5 where B表主鍵 inselect A表主鍵 from deleted) 6 end

實例測試:

刪除Info_Stu中的一條記錄時,刪除Info_Borrow中相同的記錄

1 create trigger triDelete_Stu2Borrow 2 on Info_Stu 3 after delete
4 as begin delete Info_Borrow 5 where Name in (select Name from deleted) 6 end

測試效果如下:

 

3.數據同步更新

如有兩張表:A表和B表,創建觸發器使當A表數據更新后B表也同步更新數據。

 1 create trigger 觸發器名稱  2 on A表  3 after update
 4 as begin
 5 update B表  6 set
 7 B.B表字段1=i.字段1  8 from 
 9 B表  B, deleted d,inserted  i 10 WHERE B.B表字段=d.字段

測試效果如下:

1 create trigger triUpdate_Stu2Borrow 2 on Info_Stu 3 after update
4 as
5 begin update Info_Borrow set Name=i.Name 6    from Info_Borrow as br,deleted d, inserted as i 7    where br.Name=d.Name 8 end

 

注:數據更新的操作涉及到了臨時表的建立:

理解觸發器里面的兩個臨時的表:deleted,inserted。注意deleted與inserted分別表示觸發事件的表“舊的一條記錄”和“新的一條記錄”。

一個數據庫系統中有兩個虛擬表用於存儲在表中記錄改動的信息,分別是:

  虛擬表inserted 虛擬表deleted
在表記錄新增時 存放新增的記錄 不存儲記錄
修改時 存放用來更新的新紀錄 存放更新前的記錄
刪除時 不存儲記錄 存放被刪除的記錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM