【数据库】触发器 两张表同步更新,带有外键约束的id

正常情况下的设置了外键约束的时不允许修改成其他值的,

主键想更新成其他值也不允许

所以思路就是先暂时关闭外键,然后先进行修改,再重新开启外键约束

启动禁用外键的代码:

--启用/禁用指定表所有外键约束   
alter table tablename  NOCHECK constraint all  
alter table tablename  CHECK constraint all

实例: 


--5、	创建一个部门的触发器,当部门id更新时,薪水表中对应的部门id全部更新
drop trigger tri_Bm_update 
go
create trigger  tri_Bm_update 
on Bm
instead of update
as
if UPDATE(id)
begin 
alter table xs  NOCHECK constraint all 
update Bm set bm.id=(select id from inserted) where Bm.id=(select id from deleted)
update Xs set xs.id=(select id from inserted) where xs.id=(select id from deleted)
alter table xs CHECK constraint all
end
go

但是有个弊端,如果你 update id的同时也更新了其他的数据,其他部分不会生效

所以我在update里加上了也同时更新其他的列,这样就没问题了

create trigger  tri_Bm_update 
on Bm
instead of update
as
if UPDATE(id)
begin 
alter table xs  NOCHECK constraint all 
update Bm
set bm.id=(select id from inserted),
bm.name=(select name from inserted),  /*在这里*/
bm.tel=(select tel from inserted)     /*在这里*/
where Bm.id=(select id from deleted)
update Xs set xs.id=(select id from inserted) where xs.id=(select id from deleted)
alter table xs CHECK constraint all
end
go

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shino_jie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值