Sql 使用过滤逻辑检查约束
我有一个表,它有一个名为“Flag”的位列,它不允许NULL。这里的要求是始终为下表中的每个Id设置Sql 使用过滤逻辑检查约束,sql,sql-server,unique-constraint,check-constraints,Sql,Sql Server,Unique Constraint,Check Constraints,我有一个表,它有一个名为“Flag”的位列,它不允许NULL。这里的要求是始终为下表中的每个Id设置Flag=1,但每个唯一Id和标志列组合仅设置1次。同时,如果有多个条目,则可以多次设置所有其他行的Flag=0 基本上,按ID分组的标志总和应始终为1。 虽然Id和Flag字段上存在唯一约束,但由于可以为同一组合多次设置Flag=0,因此不能使用该约束 有什么建议吗 --当前数据集 drop table if exists #test; go create table #Test (Id_pk
Flag=1
,但每个唯一Id和标志列组合仅设置1次。同时,如果有多个条目,则可以多次设置所有其他行的Flag=0
基本上,按ID分组的标志总和应始终为1。
虽然Id和Flag字段上存在唯一约束,但由于可以为同一组合多次设置Flag=0
,因此不能使用该约束
有什么建议吗
--当前数据集
drop table if exists #test;
go
create table #Test (Id_pk int identity(1,1) not null, id int not null, Flag bit not null)
Insert into #Test (id, Flag)
values (12, 0), (12,0), (12, 0), (12,0), (12, 1), (12,1), (13,0), (13, 0), (14,1), (14,1), (20,1), (20,0), (30,1), (40,0)
select * from #Test
——期望的结果
drop table if exists #test;
go
create table #Test (Id_pk int identity(1,1) not null, id int not null, Flag bit not null)
Insert into #Test (id, Flag)
values (12, 0), (12,0), (12, 0), (12,0), (12, 0), (12,1), (13,0), (13, 1), (14,0), (14,1), (20,1), (20,0), (30,1), (40,1)
select * from #Test
您不是在寻找
检查
约束。您需要过滤的唯一约束:
create unique index unq_test_id_flag
on #test(id)
where flag = 1;
是一个dbfiddle。为了测试您的解决方案,我们不能在当前数据集表上创建这样一个唯一的约束/索引。但事实并非如此…@enigma6205。道歉。我只是输入了完全错误的语法。现在已经修好了,太棒了!谢谢你。我没有意识到我们可以使用覆盖索引来实现唯一性!我们仍然允许ID具有Flag=0。这才是真正的挑战。@enigma6205。是的,就像DB小提琴一样。