Skip to content

Instantly share code, notes, and snippets.

@rruntsch
Last active March 22, 2022 19:02
Show Gist options
  • Save rruntsch/7ab8f4d05e40e795ce429a02cc162638 to your computer and use it in GitHub Desktop.
Save rruntsch/7ab8f4d05e40e795ce429a02cc162638 to your computer and use it in GitHub Desktop.
Get the primary keys for all user-defined tables in the SQL Server database.
-- File Name: get_pk.sql
-- Description: Get the primary keys.
USE AdventureWorks2019;
GO
SELECT
SCHEMA_NAME(tab.schema_id) AS [Schema]
, pk.name AS [Primary Key Name]
, tab.name AS [Table Name]
, col.name AS [Column Name]
, ic.index_column_id AS [Column ID]
from sys.tables tab
INNER JOIN sys.indexes pk
ON tab.object_id = pk.object_id
AND pk.is_primary_key = 1
INNER JOIN sys.index_columns ic
ON ic.object_id = pk.object_id
AND ic.index_id = pk.index_id
INNER JOIN sys.columns col
ON pk.object_id = col.object_id
and col.column_id = ic.column_id
ORDER BY [Schema], [Primary Key Name], [Column ID];
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment