2014-10-31 87 views
0

我想重新創建最近被刪除的外鍵約束,並且SQL Server不讓我。下面是SQL Server Management Studio中給我的DDL:創建外鍵約束的SQL Server錯誤

/* 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 

,這裏是我得到的錯誤,當我運行它:

消息547,級別16,狀態0,第1行
ALTER TABLE語句與FOREIGN KEY約束「FK_CleansedData_CleansingOperations」衝突。衝突發生在數據庫「NetVis203」,表「dbo.CleansingOperations」,列「CleansingOperationID」。

Msg 3902,Level 16,State 1,Line 1
COMMIT TRANSACTION請求沒有對應的BEGIN TRANSACTION。

這是什麼意思?據我所知,這是說約束與自身「衝突」!

回答

4

這意味着,有一個在CleansedData的行不具有CleansingOperations

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

對應的行應該不返回行的發言工作。

有一個NOCHECK關鍵字,它可以解決錯誤,但更好地瞭解哪些行會違反外鍵。

錯誤消息的原因是SQL Server想象外鍵已就位,然後在提交語句之前斷言所有行滿足約束。第二個錯誤信息的原因與錯誤處理有關(我永遠也無法得到)。

+0

非常好,這是解釋給我,給我足以解決它。乾杯。 – user41013 2014-10-31 16:18:52