SQL Server 2005 Unique constraint on two columns

2019-02-05 12:58发布

问题:

How do you add a unique constraint in SQL Server 2005 to two columns? So lets say that I have:

PK, A, B ...
x1  1  1
x2  1  2
x3  2  1
x4  2  2

I should not be able to add another row 'x5' and have the values for A and B be 1,1 as they are already in the database in x1?

Ok we managed to get it to work and thanks to OMG. Go to the table view, select the two columns, right click and select 'indexes/keys' - general tab, select the columns you want to be unique and then set 'is unique' to true. This is using the table designer.

Thanks.

回答1:

In SQL Server, a unique constraint is really implemented as a unique index. Use:

CREATE UNIQUE INDEX <uix_name> ON <table_name>(<col_A>, <col_B>)

For more info, see this MSDN page.



回答2:

ALTER TABLE YourTable
ADD CONSTRAINT UQ_YourTable_ConstraintName UNIQUE(A, B)