Alter table to add primary key in sql server

alter table to add primary key in ms sql server

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

Implementation :

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.

  1. Using SQL Server Management Studio
  2. 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.

alter table to add primary key in ms sql server using sql server management studio

 



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.

For example to add primary column to ID column of TestTable below sql query can be used.

Conclusion:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *