T-SQL Tutorial

How to check if a primary key exists


To check if a primary key exists on a table uses the system stored procedure named SP_PKEYS or view INFORMATION_SCHEMA.





Example

USE tempdb;
GO
EXEC sp_pkeys
@table_name = 'EMPLOYEES',
@table_owner = 'dbo',
@table_qualifier = 'tempdb';
GO

USE tempdb;
GO
EXEC sp_pkeys
@table_name = 'EMPLOYEES';
GO

select *
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE='PRIMARY KEY';

See also: SP_PKEYS