Saturday, June 21, 2008

Find Primary Keys

One design aspect that all tables should have is a primary key. The primary key is the main entry way into your dataset, so that when you access your data you are guaranteed to only affect one row of data. Having primary keys are not only a good design feature they also play an important role in replication and data updates especially when there may be duplicate rows of data. So how can you determine what tables have primary keys and what tables do not have primary keys?

Primary keys guarantee a unique row of data in your table. Some of the design aspects of a primary key are as follows:

* can be one or more columns
* column values can not be null
* the column or combination of columns must be unique
* there can only be one primary key on a table



Query 1 - Tables with primary keys

SQL 2005

SELECT c.name, b.name, a.name
FROM sys.key_constraints a
INNER JOIN sys.tables b ON a.parent_object_id = b.OBJECT_ID
INNER JOIN sys.schemas c ON a.schema_id = c.schema_id
WHERE a.type = 'PK'

SQL 2000

SELECT c.name, a.name, b.name
FROM sysobjects a
INNER JOIN sysindexes b ON a.id = b.id
INNER JOIN sysusers c ON a.uid = c.uid
WHERE (b.status & 2048)<>0


Query 2 - Tables without primary keys

SQL 2005

SELECT c.name, b.name
FROM sys.tables b
INNER JOIN sys.schemas c ON b.schema_id = c.schema_id
WHERE b.type = 'U'
AND NOT EXISTS
(SELECT a.name
FROM sys.key_constraints a
WHERE a.parent_object_id = b.OBJECT_ID
AND a.schema_id = c.schema_id
AND a.type = 'PK' )

SQL 2000

SELECT c.name, a.name
FROM sysobjects a
INNER JOIN sysusers c ON a.uid = c.uid
WHERE xtype = 'U'
AND NOT EXISTS
(SELECT b.name
FROM sysindexes b
WHERE a.id = b.id
AND (b.status & 2048)<>0)

No comments: