如何为表的以下验证创建约束 下面的查询应始终返回零行。
select Col1,Col2,count(*) from Table
where Col2=1
group by Col1,Col2
having count(*)>1
为了更好地理解我也提供数据
第2列值应只有1或0个值
Column2每个Column1值的值应始终为1,并且可能有多个0
Column1 Column2
1 1
1 0
1 0
1 1 X This is wrong. Reason: This combination should be unique (1,1)
2 1
2 1 X This is wrong. Reason: This combination should be unique (2,1)
2 0
3 1
3 1 X This is wrong. Reason: This combination should be unique (3,1)
3 0
答案 0 :(得分:0)
这有效
create function f1()
returns int
begin
return(select 0 from Table1
where Col2=1
group by Col1,Col2
having count(*)>1)
end
create table table1(Col1 int, Col2 int)
alter table table1 WITH NOCHECK add constraint ck_table1 check(dbo.f1()>0)