Loading ...

SQL: Find table name by primary key | CodeAsp.Net

SQL: Find table name by primary key

 /5
0 (0votes)

Today, I wanted to get the table based on primary key. I was having primary key name with me and my goal was to get table name having that primary key. Below is the script I used to find that:

SELECT KU.table_name as tablename,column_name as primarykeycolumn
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_NAME='<PrimaryKeyName>'
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;

Comments (no comments yet)

Top Posts