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表中插入一条记录

 


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值