如何基于 2 列创建 SQL 唯一约束?

我有一张这样的桌子:

|UserId   |  ContactID |  ContactName 
---------------------------------------
| 12456   |  Ax759     |  Joe Smith
| 12456   |  Ax760     |  Mary Smith
| 12458   |  Ax739     |  Carl Lewis
| 12460   |  Ax759     |  Chuck Norris
| 12460   |  Bx759     |  Bruce Lee

我需要向该表添加一个约束,以便没有用户可以拥有重复的联系人 ID.用户从各种外部系统导入数据,因此 ContactId 不会全面唯一,但会在每个用户的基础上唯一.

I need to add a constraint to this table so that no user can have duplicate contact id's. The users are importing data from various external systems so ContactId will not be unique across the board but will be unique on a per user basis.

我知道如何基于单列创建唯一和非空约束,但如何创建跨两列的唯一约束?

I know how to create Unique and Non-Null contraints based on single columns but how can I create a unique contraints across 2 columns?

推荐答案

你可以试试这个:

CREATE UNIQUE CLUSTERED INDEX index_name ON TABLE (col1,col2)

CREATE UNIQUE NONCLUSTERED INDEX index_name ON TABLE (col1,col2)

ALTER TABLE [dbo].[TABLE] ADD CONSTRAINT
    UNIQUE_Table UNIQUE CLUSTERED
    (
       col1,
       col2
    ) ON [PRIMARY]

相关文章