如果我理解你在做什么,你就不需要 PL/SQL,你只需要使用 coalesce 和 case 表达式进行简单的更新 - 诚然,两者都有很多术语,所以有点笨拙。
使用一个非常简化的表,只需要担心四列,再加上您要更新的第 41 列和第 42 列:
create table your_table (c1 number, c2 number, c3 number, c4 number, c41 number, c42 number);
insert into your_table (c1, c2) values (11, 12);
insert into your_table (c1, c2, c3) values (23, 24, 25);
您可以通过以相反的顺序合并所有其他列来获得c42 值:
coalesce(c4, c3, c2, c1)
或者在你的情况下:
coalesce(c40, c39, c38, c37, ..., c4, c3, c2, c1)
您可以使用以下 case 表达式获取该列的位置:
case
when c40 is not null then 40
when c39 is not null then 39
...
when c4 is not null then 4
when c3 is not null then 3
when c2 is not null then 2
when c1 is not null then 1
end;
您可以通过查询来查看值(使用我的简化表):
select c1, c2, c3, c4,
coalesce(c4, c3, c2, c1) as c41,
case
when c4 is not null then 4
when c3 is not null then 3
when c2 is not null then 2
when c1 is not null then 1
end as c42
from your_table;
C1 C2 C3 C4 C41 C42
---------- ---------- ---------- ---------- ---------- ----------
11 12 12 2
23 24 25 25 3
你可以只更新:
update your_table
set c41 = coalesce(c4, c3, c2, c1),
c42 =
case
when c4 is not null then 4
when c3 is not null then 3
when c2 is not null then 2
when c1 is not null then 1
end;
2 rows updated.
select * from your_table;
C1 C2 C3 C4 C41 C42
---------- ---------- ---------- ---------- ---------- ----------
11 12 12 2
23 24 25 25 3
如果这是您要经常做的事情,那么您可以创建这些虚拟列,这样它们就会自动计算并始终保持最新。