建立触发器,当roomname表更新时同时更新classroom表。roomname和classroom有外键约束。
create trigger UpdateRoomName
on roomname
instead of update
as
update classroom set room_name=(select room_name from inserted) where room_name=(select room_name from deleted)
update roomname set room_name=(select room_name from inserted) where room_name=(select room_name from deleted)
当执行代码update roomname set room_name='1号机房' where room_name='4101'时 报出错误如下:
消息 547,级别 16,状态 0,过程 UpdateRoomName,第 5 行
UPDATE 语句与 FOREIGN KEY 约束"FK_classroom_roomname"冲突。该冲突发生于数据库"Mclass",表"dbo.roomname", column 'room_name'。
sql??????????? sql?server 触发器 外键约束 数据库更新
------解决方案--------------------
这个可以不用触发器的,你这样肯定是有问题的,因为有附表引用主表的数据,而你想修改为新的数据,那么就会报外键约束错误的。
用级联更新就可以了:
create table roomname(room_name varchar(50) primary key )
create table classroom
(
room_name varchar(50) foreign key references roomname(room_name) on update cascade --级联更新
)
insert into roomname
values('4101')
insert into classroom
values('4101')
--删除主表中udi 为2的记录,没有报错
update roomname
set room_name = '1号机房'
where room_name = '4101'
--自动更新
select * from classroom
/*
room_name
1号机房
*/