Quantcast
Channel: SQL Server 2005 – SQL Steve
Viewing all articles
Browse latest Browse all 17

How to: list all primary keys in a database

$
0
0

I recently had the following question posted to this site:

Hello,

I’d think this is a simple question/problem.  I want to get the primary key name for each table in my schema.  By doing so, it will make my search easier when looking at the database.  I have schema X with many tables.  I want to know the primary key to each table and return it in a report form.  So, basically my question is, “Give me the column name of each primary key of each table in schema X.”  Is there a simple SQL statement to do this?

Thank you.

The following query allows you to view all primary keys for all user tables in the current database.  You can tweak it to return results for a given schema or any other set of parameters.

SELECT
S.name AS SchemaName,
O.name AS TableName,
IX.name AS IndexName,
IC.column_id AS ColumnId,
C.name AS ColumnName
FROM
sys.indexes AS IX
INNER JOIN
sys.index_columns AS IC
ON
IX.object_id = IC.object_id AND IX.index_id = IC.index_id
INNER JOIN
sys.columns AS C
ON
IC.object_id = C.object_id AND IC.column_id = C.column_id
INNER JOIN
sys.objects AS O
ON
C.object_id = O.object_id
INNER JOIN
sys.schemas AS S
ON
O.schema_id = S.schema_id
WHERE
IX.is_primary_key = 1
AND
O.type_desc = ‘USER_TABLE’
ORDER BY
SchemaName,
TableName,
IndexName,
ColumnId
GO

Please send me any questions you have about SQL Server and I’d be glad to answer them here.  Smile


Filed under: SQL Server 2005, SQL Server 2008, T-SQL Tagged: SQL Server

Viewing all articles
Browse latest Browse all 17

Trending Articles