Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

Check if a primary key constraint exists in SQL server

$
0
0
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.

Following example to check if a primary key exists


CREATETABLEPRODUCT
(
IDINTNOTNULLIDENTITY(1,1),
SKUVARCHAR(20)NOTNULL,
TITLEVARCHAR(200)NOTNULL,
PRICEMONEYNOTNULL,
DESCRIPTIONVARCHAR(2000)  NULL,
DTCREATEDATETIMENULL
CONSTRAINTpk_Product_IDPRIMARYKEY (ID)
)

IFOBJECT_ID('dbo.pk_Product_ID')ISNULL
  ALTERTABLEPRODUCTADDCONSTRAINTpk_Product_IDPRIMARYKEY(ID) 
ELSE
  PRINT'Product table already has primary key'

DROPTABLEPRODUCT





Viewing all articles
Browse latest Browse all 265

Latest Images

Trending Articles



Latest Images