How to place unique contraint on multiple column

蹲街弑〆低调 提交于 2019-12-10 00:56:54

问题


EmpID DeptID

1     1
1     2
2     1
3     2
4     5
5     2
1     1   
2     1   

I would like to have a constraint that will make sure that the pair of field is always unique ,such data as last two shown in the example should not be insert-able into the table .in the above table please note that last two rows are duplicates ,I would like to prevent such data from occuring . How do I achieve this in sqlserver 2005.Thanks


回答1:


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)
)



回答2:


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)




回答3:


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




回答4:


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)


来源:https://stackoverflow.com/questions/4968354/how-to-place-unique-contraint-on-multiple-column

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