简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM