Tuesday 31 May 2011

Getting the Primary Key Column Name in SQL Server 2008 R2

This might be something that is obvious to most people working in SQL Server, but for me this was a new one.

I needed to get the column name for the primary key in a table - I am working on a migration just now (no great surprise there ;)) and I needed to get this column name in order to carry out some double posting (once in the new system and next in the old system).

It was surprisingly easy to do this

 SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE TABLE_NAME = ''
This simple piece of code gets the name of the column that is your primary key. Short and simple and a new one for myself.