两张表数据同步 (添加、删除、修改 触发器)

本文介绍了一个SQL触发器的具体实现案例,展示了如何通过触发器在不同表间同步数据变更,包括插入、更新和删除操作。
--建立环境

create table table1 (sno varchar(10),sname varchar(10))
create table table2 (sno varchar(10),sname varchar(10))

go

create trigger t_table1 on table1
after 
delete,insert,update
as
begin
    
delete from table2 where sno in (select sno from deleted)

    
if not exists (select 1 from table2 a,inserted i where a.sno=i.sno)
        
insert into table2 
        
select * from inserted
    
else 
        
update a set a.sname=i.sname from table2 a,inserted i where a.sno=i.sno
end

go


/**********插入记录************/

insert into table1
select '0001','aa' union all
select '0002','bb' union all
select '0004','dd'  

select * from table1
select * from table2


--table1
/*
  
sno     sname
-----  ------- 
0001    aa
0002    bb
0004    dd


--table2
sno      sname
------  -------
0001    aa
0002    bb
0004    dd
*/


/********删除记录*************/
delete from table1 where sno='0004'

select * from table1
select * from table2

--table1
/*
  
sno     sname
-----  ------- 
0001    aa
0002    bb

--table2
sno      sname
------  -------
0001    aa
0002    bb
*/



/***********更新记录************/
update table1 set sname='cc' where sno='0002'

select * from table1
select * from table2

--table1
/*
  
sno     sname
-----  ------- 
0001    aa
0002    cc

--table2
sno      sname
------  -------
0001    aa
0002    cc
*/


/********删除测试**********/

drop table table1,table2
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值