Powered by Blogger.

Saturday, February 15, 2014

Add Primary Key Constraint to existing table in sql server 2008




In this post we will discuss how we can add Primary Key Constraint to existing table in sql server 2008.

Also you can check my previous posts on:

- File upload and thumbnail creation in Asp.Net

- Triggers in sql server 2008

- Download professional Asp.Net 4.5 in C# book pdf free

We can drop Primary Key Constraint by writing a query as well as we can drop by using Object Explorer.

By using Query:
Below is the query to add a primary key to an existing table:

ALTER TABLE Employees
   ADD CONSTRAINT PK_Employees_ID PRIMARY KEY (ID)

Here ID is the Column name and PK_Employees_ID is the Constraint name.

Similarly if you want to make 2 columns as primary key then you have to write the query like below:

ALTER TABLE Employees
   ADD CONSTRAINT PK_Employees_IDAGE PRIMARY KEY (ID,AGE)

Here both ID and AGE column will be the primary key.

By Using Object Explorer:
Right click on the table -> Click on Design

or

Right click on the column for which you want to make primary key and then click on Modify.

The above step will open the table in Table Designer mode.

Now Right-click the row with the primary key and choose Set Primary Key as shown in the fig below:


Here ID was the primary key column. But the default Constraint name will come as "PK_YourTableName".



0 comments

Post a Comment