如果唯一有效的情况是按顺序填写字段,没有空白,我认为这就是您所说的,那么您可以计算出填充的“最高”字段和填充的字段数,并且比较它们。如果我们之间存在差距,那么这两个数字将会不同。例如:
select field1, field2, field3, field4, field5 from (
select field1, field2, field3, field4, field5,
case when field1 is not null then 1 else 0 end
+ case when field2 is not null then 1 else 0 end
+ case when field3 is not null then 1 else 0 end
+ case when field4 is not null then 1 else 0 end
+ case when field5 is not null then 1 else 0 end as cnt,
greatest(case when field1 is not null then 1 else 0 end,
case when field2 is not null then 2 else 0 end,
case when field3 is not null then 3 else 0 end,
case when field4 is not null then 4 else 0 end,
case when field5 is not null then 5 else 0 end) as grt
from my_table
)
where cnt != grt;
SQL 小提琴演示。
正如Michael-O指出的那样,您可以使用nvl2
而不是case
(在另一个 SQL Fiddle中显示),这是非标准的,但可以说更清晰:
select field1, field2, field3, field4, field5 from (
select field1, field2, field3, field4, field5,
nvl2(field1, 1, 0) + nvl2(field2, 1, 0) + nvl2(field3, 1, 0)
+ nvl2(field4, 1, 0) + nvl2(field5, 1, 0) as cnt,
greatest(nvl2(field1, 1, 0), nvl2(field2, 2, 0), nvl2(field3, 3, 0),
nvl2(field4, 4, 0), nvl2(field5, 5, 0)) as grt
from t42
)
where cnt != grt;
如果您想强制执行此操作,您可以添加一个检查约束来进行相同的比较:
alter table my_table add constraint my_check check (
case when field1 is not null then 1 else 0 end
+ case when field2 is not null then 1 else 0 end
+ case when field3 is not null then 1 else 0 end
+ case when field4 is not null then 1 else 0 end
+ case when field5 is not null then 1 else 0 end
= greatest(case when field1 is not null then 1 else 0 end,
case when field2 is not null then 2 else 0 end,
case when field3 is not null then 3 else 0 end,
case when field4 is not null then 4 else 0 end,
case when field5 is not null then 5 else 0 end));
由于您使用的是 11gR2,因此您也可以使用虚拟列执行此操作:
alter table my_table add cnt generated always as
(case when field1 is not null then 1 else 0 end
+ case when field2 is not null then 1 else 0 end
+ case when field3 is not null then 1 else 0 end
+ case when field4 is not null then 1 else 0 end
+ case when field5 is not null then 1 else 0 end);
alter table my_table add grt generated always as
(greatest(case when field1 is not null then 1 else 0 end,
case when field2 is not null then 2 else 0 end,
case when field3 is not null then 3 else 0 end,
case when field4 is not null then 4 else 0 end,
case when field5 is not null then 5 else 0 end));
alter table my_table add constraint my_check check (cnt = grt);
...但除了支票本身可能更清晰之外,我认为它不会增加太多。