We are mostly creating primary key on column while creating tables, But sometime we also need to have it after creating table or on existing table as per need, So i am sharing the script to add primary key on table.
We can create a primary key on table with two options like i mentioned in the code below,
-- Option #1 ALTER TABLE TableName ADD PRIMARY KEY (ColumnName) GO -- Option #2 ALTER TABLE TableName ADD CONSTRAINT PK_TableName_ColumnName PRIMARY KEY(ColumnName) GO
In option #1 constraint will be created with default name as per system and in option #2 constraint will be created with the same name which we have mentioned.