2016-12-15 10 views
1

2つの行:AccountIDPartnerAccountIDを含むテーブルがあります。両方の列で重複を避ける必要があります。意味は、エントリが存在する場合:A&Bがすでに存在するときにSQLでB&Aエントリを防止する

| AccountID | PartnerAccountID | 
| 2   | 1    | 

制約でそれを行うにはどのような方法を:私は次のようにも存在しないことを確認する必要があります

| AccountID | PartnerAccountID | 
| 1   | 2    | 

を?

答えて

4

あなたは表現上の一意のインデックスを作成することができればそれはいいだろう:

create unique index unq_t_AccountID_PartnerAccountID 
    on t((case when AccountID < PartnerAccountID then AccountId else PartnerAccountID end), 
     (case when AccountID < PartnerAccountID then PartnerAccountIDelse AccountId end) 
     ); 

をしかし、あなたが計算列として列を作成して、インデックスを作成することで、ほぼ同じことを行うことができます

alter table t add minid as (case when AccountID < PartnerAccountID then AccountId else PartnerAccountID end); 

alter table t add maxid as (case when AccountID < PartnerAccountID then PartnerAccountIDelse AccountId end); 

create unique index unq_t_minid_maxid on t(minid, maxid); 
0

2つの列の重複を単に無視するトリガーの代わりにトリガーを作成することもできます。利点は、情報が既に格納されている場合(つまり、もう一方の方法で)トランザクションを中止する必要がないことです。このようなトリガーがどのように見えるかを試してみましょう。

CREATE TRIGGER tr_t ON t 
    INSTEAD OF INSERT 
    AS 
    BEGIN 
    INSERT t 
    SELECT AccountID, PartnerAccountID 
    FROM inserted 
    where not exists (select * from t2 where t2.AccountID = ParnterAccountID and t2.ParnterAccountId = AccountID); 
    END 
関連する問題