I want to make a check constraint or a unique index to validate that I'm not creating duplicates within my table based on 2 columns, I do not want the same two IDs in these columns.
Thinking about something like below: (but this isn't possible)
CREATE UNIQUE INDEX entity_merge_no_recursive_merge_request_index on ENTITY_MERGE (
TYPE_CODE,
CONCAT(
IIF(INTO_ID > FROM_ID, INTO_ID, FROM_ID),
'|',
IIF(INTO_ID < FROM_ID, INTO_ID, FROM_ID)
)
)
Example of what I would like to achieve:
| ID | TYPE_CODE | FROM_ID | TO_ID |
|---|---|---|---|
| 1 | PERSON | 3 | 5 |
| 2 | USER | 3 | 5 |
| 3 | PERSON | 5 | 3 |
I want to make sure that inserting the last one here would have failed, because it's the same as ID 1 but reversed.
And it's important to not have any rules on FROM_ID to be higher or lower than TO_ID as it should be possible to merge any 2 records and either have some automation or a user via frontend to choose who is the winner record. And this would inactivate the FROM_ID record.
(TYPE_CODE, IIF(INTO_ID > FROM_ID, INTO_ID, FROM_ID), IIF(INTO_ID < FROM_ID, INTO_ID, FROM_ID))is enough. But AFAIR SQL Server does not allow to create index by an expression... so create generated column(s) and use it in the index. – Akina Mar 04 '22 at 12:29CHECK CONSTRAINTwith a function is what you'd need to use instead. – J.D. Mar 04 '22 at 13:03FROM_IDis less (or equal depending on your business logic) thanTO_IDand make sure that you enter the data correctly. Then you can use normal unique index and also it will be easier for you to work with such data. – Lukas.Navratil Mar 04 '22 at 13:10FROM_IDis required to be higher or lower thanTO_ID, because it will have side effects. – Jeggy Mar 04 '22 at 13:45