Question

I need to define unique index key in my table using SQL Server.

For example:

ID    Contact1     Contact2    RelationType
-------------------------------------------------------------------
1     1            2           sister       // 1 is the 2nd sister
2     3            4           brother      // 3 is the 4th brother
3     5            1           father       // 5 is the 1st father
4     2            1           sister       // bad entry !!!

Now, how can i prohibit inserting a wrong data like the 4th ID in the table above using an unique index key?

Was it helpful?

Solution

You could create a computed column that contains a character representation of the two numbers (smaller one first) combined then create a unique constraint on the computed column.

case when Contact1 > Contact2 then convert(varchar, Contact2) + convert(varchar, Contact1)
else convert(varchar, Contact1) + convert(varchar, Contact2)

This solution would allow entering 5, 3 but not 3, 5 IF 5, 3 already exists.

OTHER TIPS

You can use a unique key in combination with a check constraint that makes you have the lower value in Contact1.

create table Relation
(
  ID int identity primary key,
  Contact1 int not null,
  Contact2 int not null,
  unique (Contact1, Contact2),
  check (Contact1 < Contact2)
)

What logic/rule are you modeling? Without knowing the answer to this it's hard to know exactly what the problem is.

That being said, it looks like your table is denormalized and may make applying constraints complicated. If you're trying to simply enforce "a contact is unique to an id", then take out the Contact 2 column and put a unique constraint on Contact 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top