Monday, March 12, 2012

How to find out the PK from a table?

Dear all experts,

I need to find out some property of a tableAs following sql statement:
select mtable.name,mcolumn.name,mtype.name,mcolumn.is_identity
from sys.tables mtable, sys.all_columns mcolumn, sys.types mtype
where mcolumn.object_id = mtable.object_id
and mcolumn.system_type_id = mtype.system_type_id
and mtable.name in ('TestTable')
order by mtable.name,mcolumn.column_id

But there is no PK information.
Follwing sql statement shows the PK name of a table, but no composite info(which fields):
select mtable.name,mkey.name
from sys.key_constraints mkey, sys.tables mtable
where mkey.parent_object_id = mtable.object_id
and mkey.type = 'PK'
and mkey.name like 'TestTable'

How can I find which fields are PK in a table?thanks...
-Winson

try using

sp_pkeys 'tablename'

|||

And I try to write another way as follow:

select mtable.name as tablename,mcolumn.name as fieldname,mtype.name as fieldtype,mcolumn.is_identity,mindex.index_id as is_pk
from sys.tables mtable inner join sys.all_columns mcolumn on mtable.object_id = mcolumn.object_id
inner join sys.types mtype on mcolumn.system_type_id = mtype.system_type_id
left join sys.index_columns mindex on mcolumn.object_id = mindex.object_id and mcolumn.column_id = mindex.column_id
where mtable.name in ('TestTable')
order by mtable.name,mcolumn.column_id,mindex.key_ordinal

|||You can also query the system view INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAIN_TYPE = 'PRIMARY KEY' joining on the table name.|||

Also, take a look at

http://msdn2.microsoft.com/en-us/library/ms345522.aspx#_FAQ16

No comments:

Post a Comment