Wednesday, March 7, 2012

how to knw which column is primary key in a table

hi all

my question is which query shud i use in sql server 2000 to get which column or columns are primary keys of table

i dont want to use any stored procedures only sql query

sp_primary_keys_rowset is one of d stored proc in sql server 2005 but i couldn't understand which query they are using

i only want to use sql query

select o.name as TableName,
c.name as ColumnName
from sysindexes i
inner join sysobjects o ON i.id = o.id and o.xtype='U'
inner join sysobjects o2 ON i.name = o2.name
and o2.parent_obj = i.id
and o2.xtype = 'PK'
inner join sysindexkeys i2 on i.id = i2.id
and i.indid = i2.indid
inner join syscolumns c ON i2.id = c.id
and i2.colid = c.colid
order by o.name,i2.keyno

|||

It is easier to use the information_schema view key_column_usage and the objectproperty function:

select table_schema + '.' + table_name as table_name, column_name
from information_schema.key_column_usage
where objectproperty(object_id(constraint_name),'IsPrimaryKey') = 1
order by table_schema, table_name

No comments:

Post a Comment