Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 SQL to identify the primary key in a table?

Author  Topic 

dbayona
Starting Member

4 Posts

Posted - 2007-10-24 : 00:43:30
Hi

I have been looking for a way to identify the primary key defined in a
table using a SQL Sentence...how can i do it?

Thanx for your support!!!

Diego Bayona

hitman
Starting Member

23 Posts

Posted - 2007-10-24 : 03:34:57
hi,
check this script

select c.object_id, c.name
from sys.indexes i
join
sys.index_columns ic
on i.object_id = ic.object_id and i.is_primary_key = 1
join
sys.columns c
on c.object_id = ic.object_id and c.column_id = ic.column_id
where i.object_id = object_id(N'TABLE_NAME')


Peter
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-10-24 : 03:39:35
Maybe this?
select * from information_schema.key_column_usage



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

hitman
Starting Member

23 Posts

Posted - 2007-10-24 : 04:30:04
quote:
Originally posted by Peso

Maybe this?
select * from information_schema.key_column_usage



E 12°55'05.25"
N 56°04'39.16"




But this query returns also foreign keys.
Peter

-----------------------
http://www.sqltips.info
-----------------------
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-10-24 : 04:36:28
If you have a standard to name Primary Key with leading PK_ it is very easy to add a
WHERE CONSTRAINT_NAME LIKE 'PK_%'



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-10-24 : 04:43:24
sp_pkeys 'your table'


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-10-24 : 11:20:39
Hrm... I did post a query for this three weeks ago in Script library
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=90466



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -