SQL: List of primary key fields within a database

The query below 1Please ensure you test any script taken from my website on a test/development machine, before running on a production server. lists the Table Name, Column Name, and Column ID for all Primary Key columns within a database

SELECT  t.name AS TableName, c.name AS ColumnName, c.colid AS ColumnID
FROM      sysindexes i
  INNER JOIN sysobjects t
      ON i.id = t.id
  INNER JOIN sysindexkeys k
    ON i.indid = k.indid AND i.id = k.ID
  INNER JOIN syscolumns c
      ON c.id = t.id AND c.colid = k.colid
WHERE  i.id = t.id
 AND   i.indid BETWEEN 1 And 254 
 AND   (i.status & 2048) = 2048
ORDER BY t.name, c.ColID

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.