2011-11-08 73 views
1

我正在看一些代碼(我沒有寫它!)來測試我們的代碼在嘗試刪除錶行時遇到兩個錯誤條件依賴關係存在。SQL異常錯誤#547&外鍵約束違規嘗試刪除

該代碼最初在消息中查找特定文本,而不是使用錯誤號。

爲了提供多語言支持,最好根據錯誤編號而不是錯誤消息來捕獲異常。

在測試中有兩套文字的代碼正在尋找,我似乎無法確定的差別是什麼,所以我不舒服只是檢查錯誤編號547

  1. DELETE語句衝突與基準約束...
  2. DELETE語句衝突以引用同一表的約束...

它是安全的假定這兩個錯誤信息將有547錯誤號碼? 乾杯 科林

回答

5

547是用於任何違反約束,不只是外鍵的錯誤代碼,例如:

create table T (
    ID int not null, 
    constraint CK_Not1 CHECK (ID != 1) 
) 
go 
insert into T (ID) values (2) 
go 
update T set ID = 1 


(1 row(s) affected) 
Msg 547, Level 16, State 0, Line 1 
The UPDATE statement conflicted with the CHECK constraint "CK_Not1". The conflict occurred in database "Flange", table "dbo.T", column 'ID'. 
The statement has been terminated. 

話雖這麼說,我想不出任何其他類型的約束,而不是外鍵,可能會違反 DELETE聲明。 (帽尖到@onedaywhen)


如果您在sys.messages看,你會看到547必須對違反約束:

select text from sys.messages where message_id=547 and language_id=1033 

The %ls statement conflicted with the %ls constraint "%.*ls". The conflict occurred in database "%.*ls", table "%.*ls"%ls%.*ls%ls.

+0

「我想不出任何其他類型的約束,除了外鍵,可能會被DELETE語句違反」 - 請參閱我的答案。 – onedaywhen

+0

你說違約約束,但2627呢?這是一個獨特的約束違規是不是?儘管如此,這並不會違反「DELETE」。我認爲你的意思是任何_check_約束違規。 – enashnash

2

Damien_The_Unbelieve: I can't think of any other type of constraint, other than foreign key, that could be violated by a DELETE statement.

這裏的另一個:

CREATE TABLE T1 (ID INTEGER NOT NULL UNIQUE); 
CREATE TABLE T2 
(
ID INTEGER DEFAULT 0 NOT NULL 
REFERENCES T1 (ID) ON DELETE SET DEFAULT 
CONSTRAINT cannot_be_zero CHECK (ID <> 0) 
); 
INSERT INTO T1 (ID) VALUES (1); 
INSERT INTO T2 (ID) VALUES (1); 
DELETE FROM T1; 

屬測試錯誤:

Msg 547, Level 16, State 0, Line 5 The DELETE statement conflicted with the CHECK constraint "cannot_be_zero".

+0

不錯 - 我會盡量在將來記住這一點 –