Search This Blog

Find Primary Keys, Foreign Keys or Constraints in a database, SQL Server 2008


I was asked to list the Primary keys in our databases then I listed using the below script. This is very useful when you have large number of tables.
SELECT 
A.CONSTRAINT_CATALOG,
A.CONSTRAINT_SCHEMA,
B.CONSTRAINT_NAME,
A.CONSTRAINT_TYPE, 
B.COLUMN_NAME,
B.ORDINAL_POSITION
 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS A Inner join 
      INFORMATION_SCHEMA.KEY_COLUMN_USAGE B  
on A.CONSTRAINT_NAME=B.CONSTRAINT_NAME