SQL - How to get the Unique Key's Column Name from Table

后端 未结 6 812
甜味超标
甜味超标 2020-12-30 03:36

I know how to get the columns from a table using the following SQL statement:

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE (TABLE_NAME = \'MYTA         


        
6条回答
  •  春和景丽
    2020-12-30 04:17

    The two that I found to work are the following, the 2nd one was from the original poster but without the TC.CONSTRAINT_TYPE = 'UNIQUE'. That condition wasn't working

    SELECT     col.name
    FROM         sys.objects AS obj INNER JOIN
                          sys.columns AS col ON col.object_id = obj.object_id INNER JOIN
                          sys.index_columns AS idx_cols ON idx_cols.column_id = col.column_id AND idx_cols.object_id = col.object_id INNER JOIN
                          sys.indexes AS idx ON idx_cols.index_id = idx.index_id AND idx.object_id = col.object_id
    WHERE     (obj.name = 'pluginUsers') AND (idx.is_unique = 1)
    

    and also

    SELECT     CCU.CONSTRAINT_NAME, CCU.COLUMN_NAME
    FROM         INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN
                          INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CCU ON TC.CONSTRAINT_CATALOG = CCU.CONSTRAINT_CATALOG AND 
                          TC.CONSTRAINT_SCHEMA = CCU.CONSTRAINT_SCHEMA AND TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
    WHERE     (TC.TABLE_NAME = 'pluginUsers')
    

    Thank you all for your posts

提交回复
热议问题