使用过滤逻辑检查约束

问题描述 投票:1回答:1

我有一个表的位列称为“ Flag”,它不允许为NULL。此处的要求是始终为下表中的每个ID设置Flag=1,但是每个唯一的ID和标志列组合仅设置1次。同时,如果条目多于1个,则所有其他行都可以设置为Flag=0

基本上按ID分组的标志的总和应始终为1。

I虽然对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
sql sql-server unique-constraint check-constraints
1个回答
1
投票

您不是在寻找check约束。您需要过滤的唯一约束:

create unique index unq_test_id_flag
    on #test(id)
    where flag = 1;

Here是db <>小提琴。

© www.soinside.com 2019 - 2024. All rights reserved.