Find Primary Keys and Columns Used in SQL Server

-Find Primary Keys and Columns Used in SQL Server

-list of table names, along with their primary keys (null if there is no primary key). It also tells you the columns used in each.

select cons.TABLE_NAME
    , cons.CONSTRAINT_NAME PK_NAME
    , cols.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons
left join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cols
on cons.CONSTRAINT_NAME = cols.CONSTRAINT_NAME
where cons.CONSTRAINT_TYPE = 'PRIMARY KEY'
order by cons.TABLE_NAME
    , cons.CONSTRAINT_NAME
    , cols.COLUMN_NAME

No comments:

Post a Comment