Reputation: 30855
I have a CustomerID column and an EffectiveDate column in a table.
I need the combination of these two to be unique.
However, I already have a primary key on an auto-numbered integer column.
What is a good way to accomplish my goal?
Thanks
Upvotes: 0
Views: 88
Reputation: 47444
CREATE UNIQUE INDEX Some_Index_Name ON My_Table (CustomerID, EffectiveDate)
Upvotes: 3
Reputation: 206
CREATE TABLE MyTable
(
<columns here>
CONSTRAINT U_ConstraintName UNIQUE (CustomerID, EffectiveDate)
)
Upvotes: 1
Reputation: 26190
Try creating a UNIQUE index on the two columns.
CREATE TABLE Example
(Col1 int NOT NULL,
Col2 int NOT NULL,
UNIQUE (Col1, Col2)
)
Example taken from this thread.
Upvotes: 1
Reputation: 64635
Simply add a unique constraint:
Alter Table TableName
Add Constraint UC_TableName_Col1Col2 Unique ( Col1, Col2 )
SQL Server creates a unique index when you create a unique constraint. If there is already a clustered index, then the above will create that index as nonclustered. However, you can be explicit like so:
Alter Table TableName
Add Constraint UC_TableName_Col1Col2 Unique Nonclustered ( Col1, Col2 )
Upvotes: 7