今天学习一个含‘增删改’三个于一体的触发器

本文介绍了一个SQL触发器的设计方案,该触发器用于在更新表A时自动同步到表B,实现插入、更新和删除操作的一致性。通过一个具体的T-SQL脚本示例展示了如何创建和使用这种触发器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

表A :ID name SEX

表B :ID name  sex

要求对一个表A进行了增删改后,表B就能增删改,要求就写一个触发器,不能是多个。

 

----- 作者:wufeng4552 

 

set nocount on
if object_id('ta')is not null drop table ta
go
create table ta(ID int ,[Name] varchar(10))
if object_id('tb')is not null drop table tb
go
create table tb(ID int ,[Name] varchar(10),Sex varchar(2))
go
if object_id('tri_Modi')is not null drop trigger tri_Modi go
create trigger tri_Modi on ta
for delete ,insert ,update
as
if not exists(select 1 from deleted)                
  
insert tb(ID,[name])select * from inserted  --insert
else if exists(select 1 from inserted)and exists(select 1 from deleted)
  
update tb set tb.[name]=inserted.[name] from inserted where tb.id=inserted.id --update  
else
  
delete b from tb b ,deleted d where b.id=d.id --del  
go
insert ta select 1,'a'
insert ta select 2,'b'
select * from tb
/*
ID          Name       Sex
----------- ---------- ----
1           a          NULL
2           b          NULL
*/
update ta set [name]='c' where id=2
select * from tb
/* ID Name Sex ----------- ---------- ---- 1 a NULL 2 c NULL */
delete ta where id=1
select * from tb
/*
ID          Name       Sex
----------- ---------- ----
2           c          NULL
*/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值