SQL Server错误创建外键约束

时间:2014-10-31 12:38:01

标签: sql-server

我正在尝试重新创建最近被删除的外键约束,而SQL Server并没有让我这么做。这是SQL Server Management Studio给我的DDL:

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.CleansingOperations SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.CleansedData ADD CONSTRAINT
    FK_CleansedData_CleansingOperations FOREIGN KEY
    (
    CleansedOperationID
    ) REFERENCES dbo.CleansingOperations
    (
    CleansingOperationID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE dbo.CleansedData SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

这是我运行时遇到的错误:

  

Msg 547,Level 16,State 0,Line 1
  ALTER TABLE语句与FOREIGN KEY约束“FK_CleansedData_CleansingOperations”冲突。冲突发生在数据库“NetVis203”,表“dbo.CleansingOperations”,列'CleansingOperationID'。

     

消息3902,级别16,状态1,行1   COMMIT TRANSACTION请求没有相应的BEGIN TRANSACTION。

这一切意味着什么?据我所见,它说的是约束与自身“冲突”!

1 个答案:

答案 0 :(得分:4)

这意味着CleansedData中有一行在CleansingOperations中没有对应的行

SELECT CleansingOperationId FROM dbo.CleansedData
EXCEPT
SELECT CleansingOperationId FROM dbo.CleansingOperations

不应返回任何行以使您的语句起作用。

有一个NOCHECK关键字可以解决错误,但更好地了解哪些行会违反外键。

错误消息的原因是,SQL Server想象外键已就位,然后在提交语句之前断言所有行都满足约束。第二条错误消息的原因与错误处理(我永远无法正确)有关。