In this tutorial i am going to explain about Alter table to add primary key in sql server 2012. In my previous tutorial i have explained about
Now we will see the implementation of Alter table to add primary key in sql server. We can add primary key to an existing table using two ways.
- Using SQL Server Management Studio
- Using T-SQL alter table statement
Add Primary Key Using SQL Server Management Studio:
- Open sql server and choose your database.
- Expand your tables.
- Select the table you want to add primary key.
- Right click the column on which you want to add primary key and select Set Primary Key option.
- Primary key will be added to that column. Please make sure the column is non null column and contains unique values else you will get the error. Refer the below image for reference.
Add Primary Key Using T-SQL alter table statement:
We can add the primary key to an existing table using alter table statement. The syntax is given below.
ALTER TABLE [TableName]
ADD PRIMARY KEY ([ColumnName])
For example to add primary column to ID column of TestTable below sql query can be used.
ALTER TABLE TestTable ADD PRIMARY KEY (ID)
Hope you learned Alter table to add primary key in sql server. Do you like this tutorial? Help us to improve. Please post your comments and feedback below.