vietdoll
vietdoll

Reputation: 1

Need a unique constraint on a table based on 3 columns where 2 columns must have the same value

I am looking to create a unique constraint on a table based on 3 columns where 2 columns must have the same value. For example:

| cat | 4 |5 |

| dog | 4 | 7 |

| cat | 4 | 7 | <--allowed since cat and 4 are the same and 3rd column is different

| cat | 5 | 1 | <--NOT allowed because cat needs to have 4 in second column

| cat | 4 | 5 | <--NOT allowed since all 3 columns are the same as first record

Is there any way to constrain this in sql server?

Upvotes: 0

Views: 91

Answers (1)

sstan
sstan

Reputation: 36473

To make this work, you would have to redesign your tables and normalize them to look like this:

Animal
------
AnimalId           int (pk)
AnimalName         varchar    [your 1st column goes here]
SomeNumber         int        [your 2nd column goes here]

YourOriginalTable
-----------------
AnimalId           int (fk)
SomeOtherNumber    int        [your 3rd column goes here]

With this table structure, you can now define the following 2 unique constraints to restrict the values the way you want:

  • Animal (AnimalName)
  • YourOriginalTable (AnimalId, SomeOtherNumber)

Upvotes: 2

Related Questions