How to get primary key with constraint name?

 Posted by vishalneeraj-24503 on 2/3/2015 | Category: Sql Server Interview questions | Views: 1678 | Points: 40
Answer:

Write below query:-
SELECT T.Table_Name ,TC.Constraint_Name, KCU.Column_Name AS 'Primary_Key_Column_name'

FROM INFORMATION_SCHEMA.TABLES T
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
ON T.table_name=TC.table_name
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
ON KCU.Constraint_Name = TC.Constraint_Name
WHERE OBJECTPROPERTY(OBJECT_ID(T.TABLE_NAME),'TableHasPrimaryKey')=1
AND T.TABLE_TYPE='BASE TABLE'
AND TC.CONSTRAINT_TYPE='primary key'
AND T.Table_Name='test1';


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response