Monday, March 12, 2012

find primary and foreign keys

I have a DB with 100 tables. I was wondering if anybody knows a quick way to list primary and foreign key with the column name for all the tables.

Your help would make my life a lot easier

thanks

Hi,

The below will list all PK's:

SELECT o.name AS 'TableName',
c.name AS 'PKColumnName'
FROM sysobjects o, sysindexes x, syscolumns c, sysindexkeys xk
WHERE o.type in ('U')
AND x.id = o.id
AND o.id = c.id
AND o.id = xk.id
AND x.indid = xk.indid
AND c.colid = xk.colid
AND xk.keyno <= x.keycnt
AND (x.status&32) = 0
AND convert(bit,(x.status & 0x800)/0x800) = 1
ORDER BY o.name, c.name

Cheers

Rob

|||Please use the INFORMATION_SCHEMA views instead of accesing system tables or using undocumented columns. The view INFORMATION_SCHEMA.KEY_COLUMN_USAGE will give the information you are looking for.

No comments:

Post a Comment