使用触发器操作表1(添加,更新,删除) 同步实现表2的操作

if object_id('TABLE_1') is not null drop table TABLE_1
CREATE TABLE TABLE_1
(
    ID
INT primary key,
    Name1
nchar(10),
    Name2
nchar(10)
)
if object_id('TABLE_2') is not null drop table TABLE_2
CREATE TABLE TABLE_2
(
    ID
INT primary key,
    Name1
nchar(10),
    Name2
nchar(10)
)

INSERT INTO Table_1 VALUES(1,'adsd','Chi')
INSERT INTO Table_2 VALUES(1,'Lei','Chi')
INSERT INTO Table_2 VALUES(2,'Alex','Chi')



create trigger tr_info on TABLE_2
for insert,update,delete
as
begin
  
if exists(select 1 from inserted) and not exists(select 1 from deleted)--insert触发器
 
begin
   
insert into Table_1 select * from inserted
 
end
 
else if exists(select 1 from inserted) and  exists(select 1 from deleted)--update触发器

 
begin
  
update b1
  
set b1.Name1=U.Name1,b1.Name2=U.Name2
  
from Table_1 b1,deleted U
  
where b1.ID=U.ID
 
end
 
else
 
begin
 
delete Table_1 where ID=(select ID from deleted)
 
end
end


--插入测试

INSERT INTO Table_2 VALUES(3,'huguo','Chi')
select * from TABLE_1

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

(
3 行受影响)

--删除测试
delete from 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 行受影响)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值