Hi all,
How to find the primary key of a table using query?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Jun 3, 2013, 3:18 AM
try following Query..
SELECT kc.name KeyName, c.NAME AS ColumnName, c.object_id, o.name
FROM sys.key_constraints kc
INNER JOIN sys.index_columns ic ON kc.parent_object_id = ic.object_id
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
INNER JOIN sys.objects o ON o.object_id = c.object_id
WHERE kc.type = 'PK' and o.name like '%table Name%'
hope this will help you.
Sunny SharmaPosted Jun 3, 2013, 2:47 AM
Use the query below, it will give you the Name of the primary key column name.
----------------------------------------------------------------------------
SELECT COL_NAME(a.object_id,b.column_id) as Column_Name from sys.indexes a
INNER JOIN sys.index_columns b
ON a.object_id=b.object_id
WHERE
a.is_primary_key=1 and OBJECT_NAME(a.object_id)='
------------------------------------------------------------------------------
*
Please accept this as answer if it helps :)
Thanks.
Kiresh GangariyaPosted Jun 3, 2013, 2:39 AM
Execute this Query
select
* from information_schema.Table_Constraints
where Table_Name = 'Table'
Ashutosh ChaturvediPosted Jun 3, 2013, 2:34 AM