Determine a table's primary key using TSQL

SqlSql ServerTsqlPrimary Key

Sql Problem Overview


I'd like to determine the primary key of a table using TSQL (stored procedure or system table is fine). Is there such a mechanism in SQL Server (2005 or 2008)?

Sql Solutions


Solution 1 - Sql

This should get you started:

SELECT 
    *
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
    JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu 
        ON tc.CONSTRAINT_NAME = ccu.Constraint_name
WHERE 
    tc.TABLE_NAME = 'TableName' AND 
    tc.CONSTRAINT_TYPE = 'Primary Key'

Solution 2 - Sql

How about

sp_pkeys 'TableName'

Solution 3 - Sql

Here's one based on system tables from SQL 2005 (99% sure it'd work in 2008). This will list all PKs for all user-defined tables, with all columns and some extra fluff that could be removed. Add parameters to pick out a table at a time.

SELECT
   schema_name(ta.schema_id)  SchemaName
  ,ta.name  TableName
  ,ind.name
  ,indcol.key_ordinal Ord
  ,col.name  ColumnName
  ,ind.type_desc
  ,ind.fill_factor
 from sys.tables ta
  inner join sys.indexes ind
   on ind.object_id = ta.object_id
  inner join sys.index_columns indcol
   on indcol.object_id = ta.object_id
    and indcol.index_id = ind.index_id
  inner join sys.columns col
   on col.object_id = ta.object_id
    and col.column_id = indcol.column_id
 where ind.is_primary_key = 1
 order by
   ta.name
  ,indcol.key_ordinal

Solution 4 - Sql

SELECT ccu.COLUMN_NAME, ccu.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
	INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu
		ON tc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME
WHERE tc.TABLE_CATALOG = 'Your_Catalog'    -- replace with your catalog
	AND tc.TABLE_SCHEMA = 'dbo'            -- replace with your schema
	AND tc.TABLE_NAME = 'Your_Table'       -- replace with your table name
	AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'

Solution 5 - Sql

exec [sys].[sp_primary_keys_rowset] @table_name= 'TableName'

Solution 6 - Sql

EXEC sp_Pkeys @tableName

Solution 7 - Sql

You're better off using INFORMATION_SCHEMA.KEY_COLUMN_USAGE, as you can access the key ordering information (ORDINAL_POSITION) which is very important to know.

SELECT 
    kcu.*
FROM 
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
    INNER JOIN 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
        ON  tc.TABLE_NAME = kcu.TABLE_NAME AND 
            tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
ORDER BY 
    tc.TABLE_NAME,
	tc.CONSTRAINT_NAME,
	kcu.ORDINAL_POSITION

Solution 8 - Sql

The simplest way is this!

select object_id from sys.objects 
where parent_object_id = OBJECT_ID(N'FACounty')
and [type] = N'PK'

Solution 9 - Sql

Can't add a comment, not enough rep points, but this is in response to those saying sp_Pkeys is not usable. Doesn't have to be a function as mentioned in another comment to an answer.

DECLARE @tbl TABLE
(
  Table_Qualifier varchar(30), 
  Table_Owner varchar(30), 
  Table_Name varchar(50), 
  Column_Name varchar(30), 
  Key_Seq int,
  PK_Name varchar(50)
)

insert into @tbl EXEC sp_Pkeys 'tablename'

select * from @tbl

Solution 10 - Sql

If you already know the name of the key you're interested in, following works:

-- Assuming you have schema "Example" and the primary key name is "PK_Item"
-- Notice that name of table is irrelevant here but is "Foobar" here
IF (OBJECT_ID('Example.PK_ITEM') IS NULL)
BEGIN
    ALTER TABLE [Example].Foobar ADD CONSTRAINT
    PK_Item PRIMARY KEY ...
END

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionreinView Question on Stackoverflow
Solution 1 - SqlStuart AinsworthView Answer on Stackoverflow
Solution 2 - SqlJason PunyonView Answer on Stackoverflow
Solution 3 - SqlPhilip KelleyView Answer on Stackoverflow
Solution 4 - SqlLukeHView Answer on Stackoverflow
Solution 5 - SqlJacob GView Answer on Stackoverflow
Solution 6 - Sqlchugh97View Answer on Stackoverflow
Solution 7 - Sqlsqlconsumer.netView Answer on Stackoverflow
Solution 8 - SqlJT TurnerView Answer on Stackoverflow
Solution 9 - SqlS WagarView Answer on Stackoverflow
Solution 10 - SqlPasi SavolainenView Answer on Stackoverflow