Primary Key Column List
To list the primary key columns, I used SQL Server to implement the standard ANSI standard , Information object_name() Details , because they are easier to work with: theres no, you must use the object_name() function to translate object_id into human-friendly names.
I use [INFORMATION_SCHEMA].[KEY_COLUMN_USAGE] to list the restrictions on the table — both primary and foreign keys; [INFORMATION_SCHEMA].CONSTRAINT_COLUMN_USAGE has similar information, but ORDINAL_POSITION missing.
[INFORMATION_SCHEMA].[TABLE_CONSTRAINTS] contains additional information about (most importantly CONSTRAINT_TYPE ), but does not list the columns to which the restriction applies.
To get only the list of columns used by the primary key, join the above two tables using the constraint name:
SELECT tc.TABLE_SCHEMA ,tc.TABLE_NAME ,tc.CONSTRAINT_NAME ,kcu.COLUMN_NAME ,kcu.ORDINAL_POSITION FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu ON kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_NAME = @TableName
Anthony geoghegan
source share