小编典典

外键约束

sql

由于FK约束,两个表相互绑定。我正在尝试通过禁用所有触发器来更新这些表,但仍然收到以下错误:-

UPDATE语句与FOREIGN KEY约束“ FK_TEST_REFERRING_REFPHYSI”冲突。数据库“ ccdb”的表“
dbo.RefPhysician”的列“ RefID”中发生了冲突。该语句已终止。”

那就是我试图完成我的任务的方式。请帮助或更新以下T-SQL:-

Begin Transaction 
Begin Try 
ALTER TABLE Test DISABLE Trigger ALL
ALTER TABLE RefPhysician DISABLE Trigger ALL
UPDATE Test 
SET RefID = '05f6c6b4-63ff-45b2-a5e2-920d5dce3e45' 
WHERE RefID = '05e6c6b4-63ff-45b2-a5e2-920d5dce3e45'; 
UPDATE RefPhysician 
SET RefID = '05f6c6b4-63ff-45b2-a5e2-920d5dce3e45' ,
SpecID = NULL ,
RefLastName = '117002 DR. BRAD DIBBLE' ,
RefFirstName = '201-190 CUNDLES RD E, BARRIE ONT L4M 4S5' ,
RefMiddleName = NULL ,
RefPhone1 = '6138365083' ,
RefPhone2 = 'print,read,866,1' ,
RefFax = '6476476464' ,
RefEmail = 'Dibble@hotmail.ca' 
WHERE 
RefID = '05e6c6b4-63ff-45b2-a5e2-920d5dce3e45'  
ALTER TABLE Test ENABLE Trigger ALL
ALTER TABLE RefPhysician ENABLE Trigger ALL
Commit Transaction 
End Try 
Begin Catch 
Rollback Transaction 
End Catch

阅读 229

收藏
2021-04-14

共1个答案

小编典典

ALTER TABLE Test NOCHECK CONSTRAINT ALL
ALTER TABLE RefPhysician NOCHECK CONSTRAINT ALL

ALTER TABLE Test WITH CHECK CHECK CONSTRAINT ALL
ALTER TABLE RefPhysician WITH CHECK CHECK CONSTRAINT ALL

重要说明: 最后两行中有趣的“ WITH CHECK CHECK”语法是为了确保SQL
Server在重新启用后再次信任FK约束。您真的不想将它们重新启用为不受信任!

但是,如果对表设计有影响,我 强烈 建议不要在主键或外键中使用可变值。如果FK约束基于内部ID,这些ID在插入后再也不会改变,则效果会更好。

2021-04-14