SQL Snippets: Select Primary Keys for All Tables in Database

Microsoft SQL ServerThis post is part of the series on SQL Snippets.

The following SQL snippet will select all primary keys for all tables in the database in which the script is run.

/*
Created by Ian Grieve of azurecurve | Ramblings of an IT Professional (http://www.azurecurve.co.uk) This code is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0 Int). */
SELECT ['Table'].TABLE_NAME ,['Column'].COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS ['Table'] INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ['Column'] ON ['Column'].CONSTRAINT_NAME = ['Table'].CONSTRAINT_NAME WHERE ['Table'].CONSTRAINT_TYPE = 'PRIMARY KEY'

I used this script recently so that I could add primary keys to the Dymamics 365 BC Table Reference website.

What should we write about next?

If there is a topic which fits the typical ones of this site, which you would like to see me write about, please use the form, below, to submit your idea.

Your Name

Your Email

Suggested Topic

Suggestion Details

Leave a Reply

Your email address will not be published. Required fields are marked *