1. 程式人生 > >使用觸發器操作表1(新增,更新,刪除) 同步實現表2的操作

使用觸發器操作表1(新增,更新,刪除) 同步實現表2的操作

ifobject_id('TABLE_1') isnotnulldroptable TABLE_1
CREATETABLE TABLE_1
(
    ID
INTprimarykey,
    Name1
nchar(10),
    Name2
nchar(10)
)
ifobject_id('TABLE_2') isnotnulldroptable TABLE_2
CREATETABLE TABLE_2
(
    ID
INTprimarykey,
    Name1
nchar(10),
    Name2
nchar(10)
)

INSERTINTO Table_1 VALUES(1,'adsd','Chi')
INSERT

INTO Table_2 VALUES(1,'Lei','Chi')
INSERTINTO Table_2 VALUES(2,'Alex','Chi')



createtrigger tr_info on TABLE_2
forinsert,update,deleteasbeginifexists(select1from inserted) andnotexists(select1from deleted)--insert觸發器
 
begininsertinto Table_1 select*from inserted
 
endelseifexists(select1from inserted) and
exists(select1from deleted)--update觸發器
 
beginupdate b1
  
set b1.Name1=U.Name1,b1.Name2=U.Name2
  
from Table_1 b1,deleted U
  
where b1.ID=U.ID
 
endelsebegindelete Table_1 where ID=(select ID from deleted)
 
endend--插入測試INSERTINTO Table_2 VALUES(3,'huguo','Chi')
select*from TABLE_1

ID          Name1      Name2
----------- ---------- ----------1           adsd       Chi      
2           Alex       Chi      
3           huguo      Chi      

(
3 行受影響)

--刪除測試deletefrom Table_2 where ID=3

ID          Name1      Name2
----------- ---------- ----------1           adsd       Chi      
2           Alex       Chi      

(
2 行受影響)
--更新測試select*from Table_2

update Table_2 set Name1='ALex2'where ID=2

ID          Name1      Name2
----------- ---------- ----------1           adsd       Chi      
2           ALex2      Chi      

(
2 行受影響)