简体   繁体   English

C#标志枚举的SQL Server唯一约束

[英]SQL Server Unique constraint for C# flag enums

Let's say I have the following columns: 假设我有以下几列:

Name | Address| Type

The Type is stored as an int in SQL Server and corresponds to a C# flag enum. 类型在SQL Server中作为int存储,并且对应于C#标志枚举。 I want to declare a unique constraint across the name, Address and type columns such that for a particular name and address, two entries do not have the same flags. 我想在名称,地址和类型列上声明一个唯一约束,以便对于特定的名称和地址,两个条目没有相同的标志。 For example the following two entries will be legal: 例如,以下两个条目将是合法的:

John | NY | 1  
John | NY | 2 

but these two will not (since the first bit is 1 for both): 但是这两个不会(因为两者的第一位都是1):

Jane | NY | 1  
Jane | NY | 3 

Is there a simple way to implement this? 有没有简单的方法来实现这一目标? Thanks! 谢谢!

You are approaching this the wrong way. 您正在以错误的方式处理此问题。

Don't stuff the flags into integer columns! 不要将标志填充到整数列中! If you really want, you can store them as bit , but tinyint is often fine: 如果确实需要,可以将它们存储为bit ,但是tinyint通常很好:

Type1 bit,
Type2 bit,
. . .

Then create unique indexes: 然后创建唯一索引:

 create unique index t_name_address_type1 on t(name, address, type1);
 create unique index t_name_address_type2 on t(name, address, type2);
 . . . 

If, for some reason, you have to store multiple values in an integer column, then you can create separate flag columns using computed columns: 如果由于某种原因必须将多个值存储在整数列中,则可以使用计算列创建单独的标志列:

alter table t add type1 as (case when intcol & 1 > 0 then 1 else 0 end);
alter table t add type2 as (case when intcol & 2 > 0 then 1 else 0 end);
. . .

Then you can create the unique indexes on the computed columns. 然后,您可以在计算列上创建唯一索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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