May 8, 2012

SQL SERVER place unique contraint on multiple column

Problem:

The problem is that we want to create two columns of a table combined unique.
Ex: consider the table below.

EmpID DeptID1     1
1     2
2     1
3     2
4     5
5     2
1     1 
1     2 
 Now we have to maintain the integrity of  these two columns combined, as you can see that last two rows are exact duplicate of 1st and 2nd rows which must not exists where as 2nd and 3rd rows are permissible.

Solution :

If you have already created a table then first remove these duplicate rows. Then execute the following SQL query in the query editor window or SQL command prompt.


ALTER TABLE table ADD CONSTRAINT AnyConstraintName UNIQUE (EmpID,DeptID)
Or at time of creating table : 
CREATE TABLE T1 (
    EmpID int not null,
    DeptID int not null,
    /* Other Columns */
    constraint PK_T1 PRIMARY KEY (EmpID,DeptID)
)
Hope this will help...


No comments:

Post a Comment