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

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



。用户正在从各种外部系统导入数据,因此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.

我知道如何创建唯一和

推荐答案

你可以试试这个:

CREATE UNIQUE CLUSTERED INDEX index_name ON TABLE (col1,col2)
or
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天全站免登陆