Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Add new primary key on table

Author  Topic 

sdw
Starting Member

6 Posts

Posted - 2010-05-03 : 03:39:53
Hi all,

I have a table which contains the following columns:-
-Emp_ID as primary key
-Emp_Name
-Emp_Dept

How can I update the table to make the Emp_Dept column primary key, I need to make it using Alter Table statement.

DBA in the making
Aged Yak Warrior

638 Posts

Posted - 2010-05-03 : 06:57:13
[code]ALTER TABLE tableName DROP CONSTRAINT PK_tableName_1
GO

ALTER TABLE tableName ADD CONSTRAINT PK_tableName_2 PRIMARY KEY (Emp_Dept)
GO[/code]
WHERE:
tableName is the name of the table
PK_tableName_1 is the name of the existing PRIMARY KEY CONSTRAINT
PK_tableName_2 is the name of the new PRIMARY KEY CONSTRAINT

However, this doesn't seem very logical. It's unlikely that every employee would have a unique department. Perhaps you meant to you meant to add the Emp_Dept to the primary key. ie, a combined key, using Emp_ID and Emp_Dept. In that case, you can use this instead:
[code]ALTER TABLE tableName ADD CONSTRAINT PK_tableName_2 PRIMARY KEY (Emp_ID, Emp_Dept)
GO[/code]

------------------------------------------------------------------------------------
Any and all code contained within this post comes with a 100% money back guarantee.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-05-03 : 10:04:28
unless all employees are linked to unique department and also all employees do have a department you cant make it primary key. Primary key field should be a unique non NULL valued field.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -