我想在我的数据库中的所有表中识别所有属于 PK(复合或非复合)的列。我怎样才能用 sql 语句做到这一点?期望的结果集:
表名 | 栏名 | 数据类型 | 约束 |
我想在我的数据库中的所有表中识别所有属于 PK(复合或非复合)的列。我怎样才能用 sql 语句做到这一点?期望的结果集:
表名 | 栏名 | 数据类型 | 约束 |
在 Sql Server 中存在一个系统视图来显示所有约束。
尝试这个:
select * from sys.key_constraints where type_desc = 'PRIMARY_KEY_CONSTRAINT'
像这样的东西:
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
我很久以前就把它复制到我的片段文件夹中了,所以我不能把它归功于它,但这很好用......
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';
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