检查唯一约束并创建一个约束的脚本

时间:2020-09-02 22:34:12

标签: sql sql-server

需要使用T-SQL脚本检查指定的列是否具有唯一的约束/索引,如果不存在则创建唯一的索引。

1 个答案:

答案 0 :(得分:1)

This link给了我编写T-SQL的想法。

共享下面的脚本以检查指定列是否存在UNIQUE索引

--Check if there are any unique indexes for a specified column.
IF NOT EXISTS (
    SELECT SC.name
    FROM sys.indexes SI
    JOIN sys.index_columns SIC 
        ON SIC.object_id = SI.object_id
        AND SIC.index_id = SI.index_id
    JOIN sys.columns SC 
        ON SC.object_id = SIC.object_id
        AND SC.column_id = SIC.column_id
    WHERE 
        SI.object_id = OBJECT_ID('zztablename')
        AND SI.is_unique_constraint = 1
        AND SC.name = 'zzid' 
)
BEGIN 
    -- Check for a specific index name
    IF NOT EXISTS (
        SELECT 1
        FROM sys.objects
        WHERE 
            object_id = OBJECT_ID(N'zzUniqueIndexName')
            AND TYPE IN (N'UQ')
        ) 
    BEGIN
        ALTER TABLE zztablename ADD CONSTRAINT zzUniqueIndexName UNIQUE (zzid);
    END
END