Reputation: 23
I need to know how to find a Primary Key in a table, also if that primary key is referenced in any foreign keys in any table.
Upvotes: 1
Views: 226
Reputation: 1926
Try this:
SELECT u.COLUMN_NAME as PK, cc.TABLE_NAME, cc.COLUMN_NAME, cc.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE u on c.CONSTRAINT_NAME = u.CONSTRAINT_NAME AND c.CONSTRAINT_TYPE = 'PRIMARY KEY'
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS r on u.CONSTRAINT_NAME = r.UNIQUE_CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cc on cc.CONSTRAINT_NAME = r.CONSTRAINT_NAME
where c.TABLE_NAME = 'your table'
Will give you all tables and columns that are referencing the primary key of the table
Upvotes: 1
Reputation: 4697
To get the priary keys from a table you can use:
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'PRIMARY KEY' and TABLE_NAME = 'yourTable'
and to get it's references you can use
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = 'yourTable'
Upvotes: 0
Reputation: 1487
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tableName'
This will give you your table structure.
Upvotes: 0