Beyondrelational

Wednesday, June 9, 2010

How to find all primary keys in a database?

Execute the following script in Query Editor to list all the primary keys, including composite primary keys, in the AdventureWorks database:
USE AdventureWorks;
SELECT
TableName = o.name,
PrimaryKey = co.name,
Rows = i.rows
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
INNER JOIN sysindexes i
ON c.constraint_name = i.name
and CONSTRAINT_TYPE = 'PRIMARY KEY'
INNER JOIN sysindexkeys k
ON i.id = k.id
AND i.indid = k.indid
INNER JOIN sys.columns co
ON i.id = co.object_id AND
k.colid = co.column_id
INNER JOIN sys.objects o
ON co.object_id = o.object_id
WHERE o.type = 'U'
AND i.rows > 0
order by TableName, PrimaryKey

No comments:

Post a Comment