3

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 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?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
benjy
  • 4,664
  • 7
  • 38
  • 43

4 Answers4

7

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
devio
  • 36,858
  • 7
  • 80
  • 143
  • This is fantastic, thanks. Apparently I have to wait 9 minutes to accept your answer as correct, but I will. – benjy Sep 19 '10 at 23:03
  • "However, I need to be able to select information about primary keys that aren't identity columns." I think this query will not full fill above requirements – Ranadeera Kantirava Apr 14 '14 at 04:15
3
SELECT name FROM sys.key_constraints WHERE type = 'PK';
SELECT name FROM sys.key_constraints WHERE type = 'UQ';
nvogel
  • 24,981
  • 1
  • 44
  • 82
1

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'
isandburn
  • 134
  • 5
1

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