我的Table2带有Table1的外键。我想创建一个触发器,在Table1更新时自动更新Table2。这就是我的想法:
create trigger MyTrigger on Table1 instead of update as
if UPDATE(Table1_ID)
begin
declare @OldID as int, @NewID as int;
select @OldID=P_ID from deleted;
select @NewID=P_ID from inserted;
update Table2 set Table1_ID=@NewID where Table2.Table1_ID=@OldID;
update Table1 set Table1_ID=@NewID where Table1_ID=@OldID;
end
它没有工作,因为我从SQL Server收到错误,表明存在与外键约束的冲突。所以我稍微修改了一下:
create trigger MyTrigger on Table1 instead of update as
if UPDATE(Table1_ID)
begin
declare @OldID as int, @NewID as int;
select @OldID=P_ID from deleted;
select @NewID=P_ID from inserted;
update Table2 set Table1_ID=null where Table2.Table1_ID=@OldID;
update Table1 set Table1_ID=@NewID where Table1_ID=@OldID;
update Table2 set Table1_ID=@NewID where Table1_ID=null;
end
有效。但是,如果触发器运行,表2中预先存在的空值显然会丢失。这样做的正确方法是什么?请注意,我在创建表时已经知道了级联选项。我只想用触发器来做。感谢。