Pages

Saturday 31 August 2013

How to get primary key name from table name in SQL.

We all know that how to check primary key of table in SQL server using graphically(using object explorer in SQL) but sometime you need to know how to find primary key of specific table using SQL query. There are many ways to find it out, some of it mention below:
Ex 1:-
SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'
Ex 2:-
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON tc.CONSTRAINT_NAME = ccu.Constraint_name
WHERE tc.CONSTRAINT_TYPE = 'Primry Key'
Ex 3(Using system stored procedure):-
EXEC sp_pkeys ‘TableName’

1 comment:

  1. Great goods from you, man. I have understand your stuff previous to and you're
    just too great. I really like what you have acquired here, certainly like what you are saying and the way in which you say it.
    You make it entertaining and you still take care of to keep it wise.
    I cant wait to read much more from you. This is really
    a wonderful site.

    My weblog :: storage options (http://selfstoragestuff.weebly.com)

    ReplyDelete