xyz
xyz

Reputation: 27827

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

Upvotes: 3

Views: 645

Answers (3)

gkrogers
gkrogers

Reputation: 8356

Try this:

CREATE TABLE tTable
    (field1 CHAR(1) NOT NULL,
     field2 INT NOT NULL,
     UNIQUE (field1, field2)
)

Upvotes: 7

Joe
Joe

Reputation:

Doesn't need to be a primary key, all it needs to be is a unique composite index.

Upvotes: 0

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

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.

Upvotes: 1

Related Questions