识别整个数据库中复合PK中包含的所有列

时间:2013-07-22 12:56:17

标签: sql sql-server sql-server-2008 tsql

我想在我的数据库中的所有表中识别属于PK(复合或非复合)的所有列。我怎么能用sql语句做到这一点?期望的结果集:

TABLE NAME |栏目名称|数据类型| CONSTRAINT |

4 个答案:

答案 0 :(得分:2)

在Sql Server中存在一个系统视图来显示所有约束。

试试这个:

select * from sys.key_constraints where type_desc = 'PRIMARY_KEY_CONSTRAINT'

答案 1 :(得分:0)

这样的事情:

select 
    t.name as [TABLE NAME],
    c.name as [COLUMN NAME],
    ty.name as [DATA TYPE],
    i.name as [CONSTRAINT]
from sys.index_columns ic
join sys.indexes i
    on ic.object_id = i.object_id
    and ic.index_id = i.index_id
join sys.columns c
    on ic.object_id = c.object_id
    and ic.column_id = c.column_id
join sys.tables t
    on ic.object_id = t.object_id
join sys.types ty
    on c.user_type_id = ty.user_type_id
where i.is_primary_key = 1

答案 2 :(得分:0)

我很久以前就将它复制到了我的代码段文件夹中,所以我不能相信它,但这很有效......

select s.name as TABLE_SCHEMA, t.name as TABLE_NAME, k.name as CONSTRAINT_NAME, c.name as COLUMN_NAME, ic.key_ordinal AS ORDINAL_POSITION
  from sys.key_constraints as k
  join sys.tables as t
    on t.object_id = k.parent_object_id
  join sys.schemas as s
    on s.schema_id = t.schema_id
  join sys.index_columns as ic
    on ic.object_id = t.object_id
   and ic.index_id = k.unique_index_id
  join sys.columns as c
    on c.object_id = t.object_id
   and c.column_id = ic.column_id
 where k.type = 'PK';

答案 3 :(得分:0)

SELECT o.name AS TableName, c.Name AS ColumnName, t.name AS DataType, kc.name AS ContraintName
FROM sys.key_constraints kc 
INNER JOIN sys.index_columns ic ON kc.parent_object_id = ic.object_id AND kc.unique_index_id = ic.index_id
INNER JOIN sys.columns c ON ic.column_id = c.column_id AND c.object_id = ic.object_id
INNER JOIN sys.objects o ON ic.object_id = o.object_id
INNER JOIN sys.types t ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE kc.type = 'PK'
ORDER BY TableName,ic.key_ordinal