Check if a primary key constraint exists in SQL server


A primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. This constraint ensures that the specific column for a table has a unique identity.
Primary key constraints. A primary key (PK) is a single column or combination of columns (called a compound key) that uniquely identifies each row in a table.

The following example to check if a primary key exists.


CREATE TABLE PRODUCT
(
ID INT NOT NULL IDENTITY(1,1),
SKU VARCHAR(20) NOT NULL,
TITLE VARCHAR(200) NOT NULL,
PRICE MONEY NOT NULL,
DESCRIPTION VARCHAR(2000)  NULL,
DTCREATE DATETIME NULL
CONSTRAINT pk_Product_ID PRIMARY KEY (ID)
)

IF OBJECT_ID('dbo.pk_Product_ID') IS NULL
  ALTER TABLE PRODUCT ADD CONSTRAINT pk_Product_ID PRIMARY KEY(ID) 
ELSE
  PRINT 'Product table already has a primary key.'

DROP TABLE PRODUCT




Related Posts

Fatal Error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails.

Problem: Sometimes, we get the following error when trying to make a connection in Rails.  FATAL ERROR: Peer authentication failed for us...