As you rightly pointed out, you can't do this easily. If you want a unique constraint, you will need to make each value unique before you apply the constraint.
Also, it's worth mentioning that you can't use WITH NOCHECK when creating the new constraint, as a unique constraint (by its very nature) requires a unique index. And you can't have a unique index without unique key values!
So, you need to do the following:
- Create a new table
- Populate it
- Add a new NOT NULL column with a default constraint (that can be removed later if necessary)
- Modify all the new column values to be unique (though this code does not guarantee that the generated identifier will be unique, and it entirely depends on what your data type and requirements are)
- Apply the unique constraint
And here's some code as an example:
IF OBJECT_ID('MyTable') IS NOT NULL
DROP TABLE MyTable
GO
CREATE TABLE MyTable (
Id INT IDENTITY PRIMARY KEY,
Employee_Id INT NOT NULL
)
INSERT INTO MyTable(Employee_Id)
VALUES(1)
INSERT INTO MyTable(Employee_Id)
VALUES(15)
INSERT INTO MyTable(Employee_Id)
VALUES(156)
INSERT INTO MyTable(Employee_Id)
VALUES(3)
INSERT INTO MyTable(Employee_Id)
VALUES(4)
INSERT INTO MyTable(Employee_Id)
VALUES(13)
INSERT INTO MyTable(Employee_Id)
VALUES(16)
INSERT INTO MyTable(Employee_Id)
VALUES(21)
ALTER TABLE MyTable
ADD Employee_Code VARCHAR(10)
GO
-- TODO: Update your new columns to be unique
-- Manually or programmatically. Note that I would not recommend
-- using the below code - it's just for example purposes
UPDATE MyTable
SET Employee_Code = LEFT(CONVERT(VARCHAR(36), NEWID()), 10)
GO
-- Create the null constraint
ALTER TABLE MyTable
ALTER COLUMN Employee_Code VARCHAR(10) NOT NULL
GO
-- Create the Unique constraint / index
ALTER TABLE MyTable
ADD CONSTRAINT MyTable_Employee_Code_Unique UNIQUE(Employee_Code)
GO
UPDATE
Actually, I worked out a better way to do this without even using DEFAULT values. Updated code above.