SQL刪除、插入觸發器

數據庫:twt001

數據表:aa,bb,cc

參考文章:點擊打開鏈接

 

基本表的建立

create table aa ([dept_id] int,[inner_code] varchar(6),[ConText] varchar(18)) 
insert aa 
select 1,'01','總公司' union all 
select 2,'0101','一分公司' union all 
select 3,'010101','一分公司第一項目部' union all 
select 4,'0102','二分公司' union all 
select 5,'010201','二分公司第二項目部' 


create table bb ([dpart_id] int,[ConText] varchar(10)) 
insert bb 
select 1,'財務辦' union all 
select 2,'人力資源部' union all 
select 3,'審計部' 


create table cc([name] varchar(4),[dept_id] int,[dpart_id] int) 
insert cc 
select '張三',1,1 union all 
select '李四',2,1 union all 
select '王二',3,1 union all 
select '陳三',4,1 union all 
select '王五',5,1 

select * from aa 
select * from bb 
select * from cc 

 

(1)刪除觸發器

--創建刪除存儲過程
create trigger dd on cc 
for delete 
as 
declare  @dept_id int 
select @dept_id=dept_id from deleted 
delete from aa where dept_id=@dept_id 


刪除CC中的一條數據

delete from cc where dept_id=2

再次查看三個表的內容

select * from aa 
select * from bb 
select * from cc 

我們可以看到,觸發器dd被觸發後使得aa表中的記錄也刪掉了

(2)插入觸發器

create trigger charu on cc 
for insert 
as 
declare @dept_id int 
declare @dpart_id int 
declare @name varchar(10) 
select @dept_id=dept_id from inserted 
select @dpart_id=dpart_id from inserted 
select @name=name from inserted 
insert aa select @dept_id,null,null 
insert bb select @dpart_id,@name 
go 

 

進行觸發:

insert cc select '李晗',100,120 
insert cc select '李晗',100,120 


查看觸發後三表結果

可以看見,每執行一次對以cc表的插入,觸發器charu將被執行,分別在aa表和bb表中插入一條記錄

 


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章