0

我需要使用SQL Server在我的表中定義唯一索引鍵。多列唯一索引鍵

例如:

ID Contact1  Contact2 RelationType 
------------------------------------------------------------------- 
1  1   2   sister  // 1 is the 2nd sister 
2  3   4   brother  // 3 is the 4th brother 
3  5   1   father  // 5 is the 1st father 
4  2   1   sister  // bad entry !!! 

現在,我怎樣才能禁止插入錯誤數據像上表中使用唯一索引鍵的第四ID?

+2

爲什麼第四個條目不好? –

+0

第四個ID Contact1和Contact2類似於第一個ID。 – Nildarar

+0

好的。 contact1和contact2代表什麼? –

回答

1

你可以創建一個包含兩個數字的字符表示計算列(較小的一個第一)聯合創建,然後在計算列上的唯一約束。

case when Contact1 > Contact2 then convert(varchar, Contact2) + convert(varchar, Contact1) 
else convert(varchar, Contact1) + convert(varchar, Contact2) 

該解決方案將允許輸入5,3而不是3,5如果5,3已經存在。

1

您可以將一個唯一鍵與檢查約束結合使用,使您在Contact1中具有較低的值。

create table Relation 
(
    ID int identity primary key, 
    Contact1 int not null, 
    Contact2 int not null, 
    unique (Contact1, Contact2), 
    check (Contact1 < Contact2) 
) 
+0

你的解決方案是真實的,但不是最好的,因爲用戶填寫數據和(contact1 Nildarar

+0

在將行插入表格之前,可以由代碼負責您的操作。沒有必要用此來打擾用戶。 –

0

您建模的邏輯/規則是什麼?在不知道這個問題的答案的情況下,很難確切地知道問題所在。

這就是說,它看起來像你的表非規範化,並可能使應用程序約束複雜。如果您試圖簡單地強制執行「某個聯繫人對某個ID唯一」,那麼請取出聯繫人2欄並在聯繫人1上添加一個唯一約束。