SQL C# 标志枚举的服务器唯一约束
SQL Server Unique constraint for C# flag enums
假设我有以下列:
Name | Address| Type
Type 在 SQL Server 中存储为 int,对应于 C# 标志枚举。我想在名称、地址和类型列中声明一个唯一约束,这样对于特定的名称和地址,两个条目没有相同的标志。例如,以下两个条目将是合法的:
John | NY | 1
John | NY | 2
但这两个不会(因为两者的第一位都是 1):
Jane | NY | 1
Jane | NY | 3
有没有简单的实现方法?谢谢!
您的处理方式有误。
不要将标志塞入整数列!如果你真的想要,你可以将它们存储为 bit
,但 tinyint
通常没问题:
Type1 bit,
Type2 bit,
. . .
然后创建唯一索引:
create unique index t_name_address_type1 on t(name, address, type1);
create unique index t_name_address_type2 on t(name, address, type2);
. . .
如果出于某种原因,您需要在整数列中存储多个值,那么您可以使用计算列创建单独的标志列:
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);
. . .
然后您可以在计算列上创建唯一索引。
假设我有以下列:
Name | Address| Type
Type 在 SQL Server 中存储为 int,对应于 C# 标志枚举。我想在名称、地址和类型列中声明一个唯一约束,这样对于特定的名称和地址,两个条目没有相同的标志。例如,以下两个条目将是合法的:
John | NY | 1
John | NY | 2
但这两个不会(因为两者的第一位都是 1):
Jane | NY | 1
Jane | NY | 3
有没有简单的实现方法?谢谢!
您的处理方式有误。
不要将标志塞入整数列!如果你真的想要,你可以将它们存储为 bit
,但 tinyint
通常没问题:
Type1 bit,
Type2 bit,
. . .
然后创建唯一索引:
create unique index t_name_address_type1 on t(name, address, type1);
create unique index t_name_address_type2 on t(name, address, type2);
. . .
如果出于某种原因,您需要在整数列中存储多个值,那么您可以使用计算列创建单独的标志列:
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);
. . .
然后您可以在计算列上创建唯一索引。