Is there a view in SQL Server that lists only primary keys?

I work with SQL Server and try to “flip” it a bit if you do. I found a system view sys.identity_columnsthat contains all the identification columns for all my tables.

However, I need to be able to select information about primary keys that are not 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?

+3
source share
4 answers

This works for SQL Server 2005 and above:

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
+7
source
SELECT name FROM sys.key_constraints WHERE type = 'PK';
SELECT name FROM sys.key_constraints WHERE type = 'UQ';
+3
source

I understand that the question has already been marked as an answer, but for some it may be useful to show how to include sys.index_columns(in addition to sys.indexes) your query in order to associate the actual primary key index in the columns of the table. 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'
+1
source

Try it...

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
+1
source

Source: https://habr.com/ru/post/1765544/


All Articles