如何基于 2 列创建 SQL 唯一约束? [英] How can I create a SQL unique constraint based on 2 columns?

查看:28
本文介绍了如何基于 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]

这篇关于如何基于 2 列创建 SQL 唯一约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆