Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine a table's primary key using TSQL

I'd like to determine the primary key of a table using TSQL (stored procedure or system table is fine). Is there such a mechanism in SQL Server (2005 or 2008)?

like image 454
rein Avatar asked Oct 06 '09 13:10

rein


People also ask

When you define a table's primary key?

There are two kinds of keys: Primary key A table can have only one primary key. A primary key consists of one or more fields that uniquely identify each record that you store in the table. Often, there is a unique identification number, such as an ID number, a serial number, or a code, that serves as a primary key.

How do I find the primary key of a schema?

If you want to get the primary key for a specific table, then you need to filter on SchemaName and TableName . IMHO, this solution is very generic and does not use any string literals, so it will run on any machine. Show activity on this post. You can also filter on the table_name column if you want a specific table.

How do you check if a table has a primary key in SQL Server?

To check if a primary key exists on a table uses the system stored procedure named SP_PKEYS or view INFORMATION_SCHEMA.


1 Answers

This should get you started:

SELECT      * FROM      INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc     JOIN      INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu          ON tc.CONSTRAINT_NAME = ccu.Constraint_name WHERE      tc.TABLE_NAME = 'TableName' AND      tc.CONSTRAINT_TYPE = 'Primary Key' 
like image 98
Stuart Ainsworth Avatar answered Oct 02 '22 16:10

Stuart Ainsworth