How to place unique contraint on multiple column

≯℡__Kan透↙ 提交于 2019-12-04 23:15:01
ALTER TABLE <YourTable, sysname, Emp> 
ADD CONSTRAINT <YourConstraintName, sysname, uix> 
UNIQUE NONCLUSTERED (EmpID,DeptID) 

(Paste into SSMS and use (CTRL + Shift + M))

Or to do this at table creation and as it sounds as though there is no alternative key use.

CREATE TABLE EMPLOYEE_DEPARTMENT(
    EmpID int NOT NULL REFERENCES EMPLOYEE(EmpID),
    DeptID int NOT NULL REFERENCES DEPARTMENT(DeptID),
 CONSTRAINT PK_EMPLOYEE_DEPARTMENT PRIMARY KEY CLUSTERED (EmpID ASC,DeptID ASC)
)

After you've gone through and removed the duplicates, run the following (substituting appropriate names)

ALTER TABLE table ADD CONSTRAINT UQ_EmpID_DeptID UNIQUE (EmpID,DeptID)

Or when creating your table:

CREATE TABLE T1 (
    EmpID int not null,
    DeptID int not null,
    /* Other Columns */
    constraint PK_T1 PRIMARY KEY (EmpID,DeptID)
)

(May as well make it the primary key, unless you've got another one in the table)

ALTER TABLE dbo.YOURTABLE ADD CONSTRAINT IX_YOURTABLE UNIQUE NONCLUSTERED (EmpID, DeptID)

select empID, deptID from table
group by empID, deptID

EDIT:

If you are saying this data must be unique in table itself, i.e. The insertion of duplicates should not be allowed, then you need to define a composite key (empID, deptID) on this table.

alter table <tablename> add constraint <compositekeyname> primary key (empID, deptID)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!