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
Unique key is a constraint in SQL Server. This constraint ensures that we cannot enter duplicate values into the columns. It means the data stored in the column is unique among the rows in the table. We can create a unique key on both single and multiple columns.
The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.
You can create a UNIQUE constraint on one or more columns of a table.
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With