打开游标以根据 oracle 中同一表的其他列值获取和更新表的列值



>我必须根据以下逻辑更新表中的最后 2 列,该逻辑有 42 列。

  • C42 的字段值(在下面的等式中替换为 N(= ("具有空值/无值的第一列位置" - 1(
  • C41 的字段值 = C(N( 列的字段值,其中 N = (列"C42"的值减去 1(

注意:表值的设置方式是,当在列中遇到第一个空值时;后面的其他列在任何特定记录中肯定为 null。表有大约 100K 条记录,它是一个中间表,其中上述计算每周重复一次,并在表中填充新值,最后两列每周再次计算。

例如:

C42 = C19   ( 20 - 1) 
C41 = C(20) when 20 columns have some value and 21st column is null

尝试创建存储过程并打开游标以获取值以进行计算,但在创建逻辑和基于逻辑更新每一行时遇到问题。有人可以建议一种有效的方法来执行上述计算逻辑并更新每条记录。提前致谢

如果我理解你在做什么,你不需要 PL/SQL,你只需要使用合并和大小写表达式进行简单的更新 - 诚然,两者都有很多术语,所以它有点笨拙。

使用一个非常简化的表,其中只有四列需要担心,加上您要更新的第 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
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

如果这是您要定期做的事情,那么您可以改为制作这些虚拟列,以便它们自动计算并始终保持最新状态。

最新更新