简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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