2

Good Day Friends,

I want to know that how to make two columns are unique in SQL server in the special manner as I explained below.

The Way I want :

------------------------- 
  User    | Friend      |  
-------------------------
  Stevan  | Johns     } 
  William | David     }This is how I want two columns to be unique. 

The Way I don't Want :

-------------------------
  User    | Friend    | 
-------------------------
 Steven   | Johns     }   
 Johns    | Steven    }This must not allow.

Steven is a friend of Johns So They are friends so I don't want Johns to add a new row saying Johns is a friend of Steven.

Steven add new row like this :

-------------------------
  User    | Friend    | 
-------------------------
 Steven   | Johns     }   

I Don't want john to add a row again Like this

-------------------------
  User    | Friend    | 
-------------------------
 Steven   | Johns     }   
 Johns    | Steven    }

I hop my question is clear, IF someone know a good answer for this , please help me. Thanks in advance for any answer

4

2 回答 2

3

执行此操作的直接方法(所有其他条件相同)是坚持第一列中的值始终排在第二列中的值之前:

CREATE TABLE Friends (
    Party1 varchar(20) not null,
    Party2 varchar(20) not null,
    constraint CK_Friend_Parties CHECK (Party1 < Party2),
    constraint CK_Friends_Unique UNIQUE (Party1,Party2)
)

如果您无法适应这种变化(这很奇怪,因为它表明关系不是对称的),您可以通过索引视图强制执行它:

create table dbo.T1 (
    Party1 varchar(20) not null,
    Party2 varchar(20) not null
)
go
create view dbo.V1
with schemabinding
as
    select
        CASE WHEN Party1 < Party2 THEN Party1 else Party2 END as NormParty1,
        CASE WHEN Party1 < Party2 THEN Party2 else Party1 END as NormParty2
    from
        dbo.T1
go
create unique clustered index IX_V1 on dbo.V1 (NormParty1,NormParty2)
go
insert into dbo.T1 (Party1,Party2) values ('Steven','John')
go
insert into dbo.T1 (Party1,Party2) values ('John','Steven')

上面的最后插入会产生错误。请注意,对于大多数意图,您会忽略视图V1- 它只是为了强制执行此约束而存在(当我使用此类表时,我通常会在它们的名称前加上前缀,DRI_以清楚地表明它并不是真正为查询而创建的。

于 2013-04-12T10:23:03.987 回答
-1

我认为,因为主键不起作用,您将不得不使用触发器来检查该行是否已经存在。

于 2013-04-12T10:20:39.720 回答