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. I've found the system view sys.identity_columns
, which contains all of the identity columns for all of my tables.
However, I ne开发者_开发百科ed 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:
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. 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
精彩评论