Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the primary key for a table in SQL Server?

What I'd like to be able to do in SQL Server 2005 somehow is with a table name as input determine all the fields that make up the primary key. sp_columns doesn't seem to have this field. Any ideas as to where to look?

like image 254
tekiegreg Avatar asked Nov 29 '22 06:11

tekiegreg


2 Answers

I use this in a code generator I wrote to get the primary key:

SELECT i.name AS IndexName, 
    OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
    COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName, 
    c.is_identity, c.user_type_id, CAST(c.max_length AS int) AS max_length, 
    CAST(c.precision AS int) AS precision, CAST(c.scale AS int) AS scale 
FROM sys.indexes AS i 
INNER JOIN sys.index_columns AS ic 
INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id 
    ON i.OBJECT_ID = ic.OBJECT_ID AND i.index_id = ic.index_id 
WHERE i.is_primary_key = 1 AND ic.OBJECT_ID = OBJECT_ID('dbo.YourTableNameHere')
ORDER BY OBJECT_NAME(ic.OBJECT_ID), ic.key_ordinal
like image 106
Micky McQuade Avatar answered Dec 04 '22 09:12

Micky McQuade


Actually, the primary key is something else than the indexes on the table. Is also something else than the clustered index. Is a constraint, so the proper place to look for it is sys.key_constraints:

select ic.key_ordinal, cl.name, ic.is_descending_key
from sys.key_constraints c
join sys.indexes i on c.parent_object_id = i.object_id
    and c.unique_index_id = i.index_id
join sys.index_columns ic on ic.object_id = i.object_id
    and ic.index_id = i.index_id    
join sys.columns cl on cl.object_id = i.object_id
    and ic.column_id = cl.column_id 
where c.type = 'PK'
    and 0 = ic.is_included_column
    and i.object_id = object_id('<tablename>')
order by ic.key_ordinal
like image 38
Remus Rusanu Avatar answered Dec 04 '22 09:12

Remus Rusanu