假设您的所有条件都表示为BIT 列,您可以使用以下格式进行约束:
alter table [table_name] add constraint [constraint_name]
check ( ( a ^ b ^ c ) = 1 AND NOT ( a & b & c ) = 1 )
这样做,您还可以在 case 语句中使用相同的条件,例如:
select a, b, c,
case when (( a ^ b ^ c ) = 1 AND NOT ( a & b & c ) = 1) then 1
else 0 end
as true_or_false
from [table_name]
把这些放在一起,我们可以用这样的脚本来演示它:
create table #bits (a bit, b bit, c bit)
create table #bits2 (a bit, b bit, c bit)
alter table #bits2 add constraint ck_xor
check ( ( a ^ b ^ c ) = 1 AND NOT ( a & b & c ) = 1 )
insert into #bits
values
( 0, 0, 0 ), ( 0, 0, 1 ), ( 0, 1, 0 ), ( 0, 1, 1 ), ( 1, 0, 0 ), ( 1, 0, 1 ), ( 1, 1, 0 ), ( 1, 1, 1 )
select a, b, c,
case when ( a ^ b ^ c ) = 1 AND NOT ( a & b & c ) = 1 then 1
else 0 end
as true_or_false
from #bits
insert into #bits2
select * from #bits
where ( a ^ b ^ c ) = 1 AND NOT ( a & b & c ) = 1
-- the below line will fail because of the check constraint
insert into #bits2 (a,b,c) values (1,1,0)
select * from #bits2
drop table #bits
drop table #bits2