SQL - 如何从表中获取唯一键的列名

时间:2010-07-05 14:44:06

标签: sql

我知道如何使用以下SQL语句从表中获取列:

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE (TABLE_NAME = 'MYTABLENAME')

但是我如何才能返回UNIQUE Key的列名?

6 个答案:

答案 0 :(得分:15)

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.CONSTRAINT_CATALOG = 'MyCatalogName'
and TC.CONSTRAINT_SCHEMA = 'MySchemaName'
and TC.TABLE_NAME = 'MyTableName'
and TC.CONSTRAINT_TYPE = 'UNIQUE'

请记住,表可能有多个唯一约束,每个约束包含多个列。您需要应用一些额外的逻辑来选择正确的逻辑。

更新 - 基于其他评论...

上述查询将找到所有UNIQUE个键约束。但是,它不会在PRIMARY KEY键约束之外找到UNIQUE个约束或UNIQUE索引。

要查找主键,请将最后一行替换为:

and TC.CONSTRAINT_TYPE = 'PRIMARY KEY'

答案 1 :(得分:7)

这样的事可能有用(未经测试):

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

答案 2 :(得分:3)

这样的事情:

Select col.name From 
sys.objects obj 
Join sys.columns col on col.[object_id] = obj.[object_id]
Join sys.index_columns idx_cols on idx_cols.[column_id] = col.[column_id] and idx_cols.[object_id] = col.[object_id]
Join sys.indexes idx on idx_cols.[index_id] = idx.[index_id] and idx.[object_id] = col.[object_id]
where obj.name = 'MYTABLENAME'
and idx.is_unique = 1

答案 3 :(得分:1)

我发现工作的两个是以下,第二个来自原始海报,但没有TC.CONSTRAINT_TYPE ='UNIQUE'。那条件不起作用

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)

以及

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')

感谢大家的帖子

答案 4 :(得分:0)

不会DESCRIBE TABLE_NAME;诀窍呢?

答案 5 :(得分:-1)

public float moveSpeed = 2.0;  // Units per second

 void Update () {
         var targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         targetPos.z = transform.position.z;
         transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
     }