What SQL query can be used to determine the primary key of a given table?

A simple question – what SQL query can be used to determine the primary key of a given table? I can easily query SQL Server's system tables to determine fields' default values, data types, names etc etc but not the primary key.

Any ideas?

[584 byte] By [MarcStevenson] at [2008-2-6]
# 1
Here is a little example

create table foo1 (a int primary key, b int);
select * from sys.objects where parent_object_id=object_id('foo1') and type='PK'

Thanks
Mirek

MirekSztajno at 2007-9-9 > top of Msdn Tech,SQL Server,SQL Server Database Engine...
# 2

Thanks but your SQL (when corrected) will give you the primary key constraint and will not tell you which field(s) make up the primary key. eg:

create table foo1 (a int primary key, b int)

select * from sysobjects
where parent_obj=object_id('foo1')
and xtype='PK'

What I'm asking is - how do you use SQL to determine the field(s) which make up the primary key on a given table?

I expected the syscolumns table to have included primary key but this is not the case.

Any ideas?

MarcStevenson at 2007-9-9 > top of Msdn Tech,SQL Server,SQL Server Database Engine...
# 3
See if this helps:

SELECT tblcons.TABLE_NAME, keycoluse.CONSTRAINT_NAME, keycoluse.COLUMN_NAME, keycoluse.ORDINAL_POSITION
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tblcons
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE keycoluse ON (tblcons.CONSTRAINT_CATALOG = keycoluse.CONSTRAINT_CATALOG) AND
(tblcons.CONSTRAINT_SCHEMA = keycoluse.CONSTRAINT_SCHEMA) AND (tblcons.TABLE_CATALOG = keycoluse.TABLE_CATALOG) AND (tblcons.TABLE_SCHEMA = keycoluse.TABLE_SCHEMA) AND
(tblcons.TABLE_NAME = keycoluse.TABLE_NAME) AND (tblcons.CONSTRAINT_NAME = keycoluse.CONSTRAINT_NAME)
WHERE tblcons.CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY tblcons.TABLE_NAME, keycoluse.CONSTRAINT_NAME, keycoluse.ORDINAL_POSITION

jclausius at 2007-9-9 > top of Msdn Tech,SQL Server,SQL Server Database Engine...
# 4

Brilliant! Jeff, this works perfectly even though it’s way over my head J

Many thanks

MarcStevenson at 2007-9-9 > top of Msdn Tech,SQL Server,SQL Server Database Engine...

SQL Server

Site Classified