SQL Server Unique constraint for values in different column

mctunoxg  于 2023-02-18  发布在  其他
关注(0)|答案(1)|浏览(134)

I have a table that has a key and an alternative key column within the same table. If a value is set in the key column, it must not be used in the alternative key column and vice versa. `

For example, this should be valid:

-----------------------------
|   Key   | alternative Key | 
|---------|-----------------|
| Key_1   | NULL            |
| Key_2   | NULL            |
| Key_3   | Key_36          |
| Key_4   | NULL            |
| ...     | ...             |
-----------------------------

But this should not be allowed:

-----------------------------
|   Key   | alternative Key | 
|---------|-----------------|
| Key_1   | NULL            |
| Key_2   | NULL            |
| Key_3   | Key_1           |
| Key_4   | NULL            |
| ...     | ...             |
-----------------------------

The root of the problem is, that my system communicates with a PLC through these keys. However, there are some use-cases where the key we send to the PLC is different from the key we display on screen. The key is always displayed on screen, but if an alternative key is present, it is used for communication instead of the key .

Is it possible to prevent this using SQL constraints or do I need to handle this in my business logic? I am using a code-first approach with C# entities using entity framework core, if that makes a difference. I don't want to change my data-model, if I don't have to.

zbdgwd5y

zbdgwd5y1#

I agree 100% with the above comments about correcting your data model. Some databases, e.g., Sql Server, support unique indexes on schema-bound views. A view like Select Key From TheTable Union All Select AlternateKey From TheTable Where AlternateKey Is Not Null could then enforce a unique constraint.

相关问题