Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Enforcing uniqueness in one column depending on another column

Apologies if I get the terminology wrong. How do I define a constraint in MSSQL Server 2005 to enforce uniqueness in one column depending on another column?

E.g. considering the last two columns:

1    A    1
2    A    2
3    A    2 <- Disallow because '2' has already appeared alongside 'A'
4    B    1
5    B    2
like image 288
xyz Avatar asked Nov 17 '25 13:11

xyz


2 Answers

Try this:

CREATE TABLE tTable
    (field1 CHAR(1) NOT NULL,
     field2 INT NOT NULL,
     UNIQUE (field1, field2)
)
like image 134
gkrogers Avatar answered Nov 19 '25 09:11

gkrogers


Create a unique constraint on the 2 columns ?

This is the most logical thing to do, since it seems that this one column is not unique, but the combination of the 2 columns must be unique.

like image 23
Frederik Gheysels Avatar answered Nov 19 '25 08:11

Frederik Gheysels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!