简体   繁体   English

检查表的列是否具有唯一约束

[英]Check if column of a table has unique constraint

I need a query which can tell me if a column of a table has unique constraint or not.我需要一个可以告诉我表的列是否具有唯一约束的查询。 If doesn't have, I have to add unique constraint.如果没有,我必须添加唯一约束。 Currently I am using below query to check if a table's column has unique constraint or not:目前我正在使用下面的查询来检查表的列是否具有唯一约束:

IF NOT EXISTS (SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
    WHERE TC.CONSTRAINT_TYPE = 'UNIQUE' AND CONSTRAINT_NAME = 'IX_Product_Users' AND TABLE_NAME = 'Product_Users')
BEGIN
    ALTER TABLE Product_Users
    ADD CONSTRAINT IX_Product_Users UNIQUE (EmpID)
END
GO

Tried this one too, but it is not able to check on which column the constraint it is:也试过这个,但它无法检查约束是在哪一列上:

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='Product_Users' AND CONSTRAINT_TYPE = 'UNIQUE'

But I think this is a wrong way cause there might be possibility that unique constraint name is different.但我认为这是一种错误的方式,因为唯一约束名称可能不同。 Is there any precise way to do this?有什么精确的方法可以做到这一点?

Rather than using the constraint name look for the same definition. 而不是使用约束名称寻找相同的定义。 something like 就像是

SELECT * 
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
    inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu 
        on cu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME 
where 
    tc.CONSTRAINT_TYPE = 'UNIQUE'
    and tc.TABLE_NAME = 'Product_Users'
    and cu.COLUMN_NAME = 'EmpID'

I would like to suggest this query:我想建议这个查询:

SELECT tc.CONSTRAINT_NAME, count(*)
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
    inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu 
        on cu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME 
where 
    tc.CONSTRAINT_TYPE = 'UNIQUE'
    and tc.TABLE_NAME = 'Product_Users'
    and cu.COLUMN_NAME = 'EmpID'
group by tc.CONSTRAINT_NAME
having count(*) = 1

The column can be envolved in a unique constraint with multiple columns, this way you will obtain the unique constrains that only have your column.该列可以包含在具有多个列的唯一约束中,这样您将获得只有您的列的唯一约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM