简体   繁体   English

SQL Server中是否有仅列出主键的视图?

[英]Is there a view in SQL Server that lists just primary keys?

I'm working with SQL Server and trying to do a little "reflection," if you will. 我正在使用SQL Server并尝试做一些“反思”,如果你愿意的话。 I've found the system view sys.identity_columns , which contains all of the identity columns for all of my tables. 我找到了系统视图sys.identity_columns ,它包含了我所有表的所有标识列。

However, I need to be able to select information about primary keys that aren't identity columns. 但是,我需要能够选择有关非标识列的主键的信息。 Is there a view that contains data about all primary keys and only primary keys? 是否有包含所有主键和主键的数据的视图? If not, how else can I get this data? 如果没有,我怎么能得到这些数据?

This works for SQL Server 2005 and higher: 这适用于SQL Server 2005及更高版本:

select OBJECT_SCHEMA_NAME(i.object_id), OBJECT_NAME(i.object_id), i.name
from sys.indexes i
where i.is_primary_key = 1
order by 1, 2, 3
SELECT name FROM sys.key_constraints WHERE type = 'PK';
SELECT name FROM sys.key_constraints WHERE type = 'UQ';

i realize that the question has already been marked as answered, but it might also be helpful to some to show how to incorporate sys.index_columns (in addition to sys.indexes ) to your query in order to tie the actual primary key index to the table's columns. 我意识到这个问题已被标记为已回答,但是对于某些人来说,如果将sys.index_columns (除了sys.indexes )合并到您的查询中以便将实际主键索引与表的列。 example: 例:

select
    t.Name as tableName
    ,c.name as columnName
    ,case when pk.is_primary_key is not null then 1 else 0 end as isPrimaryKeyColumn
from sys.tables t
inner join sys.columns c on t.object_id = c.object_id
left join sys.index_columns pkCols 
    on t.object_id = pkCols.object_id 
    and c.column_id = pkCols.column_id
left join sys.indexes pk 
    on pkCols.object_id = pk.object_id 
    and pk.is_primary_key = 1
where 
    t.name = 'MyTable'

Try this... 尝试这个...

SELECT KC.TABLE_NAME, KC.COLUMN_NAME, KC.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE KC
WHERE OBJECTPROPERTY(OBJECT_ID(KC.CONSTRAINT_NAME), 'IsPrimaryKey') = 1
AND COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM