【问题标题】:Looping in PLSQLPLSQL 中的循环
【发布时间】:2023-03-25 22:19:02
【问题描述】:

您是否曾经在做某事,找到了一种更简单的方法,完成了项目,但仍想获得第一种工作方式?

这就是我现在所处的位置。我想计算最近的数字和前面的数字不相等的列中的实例数。我决定用一个while循环来做到这一点。

例如,

4
3
2
1
1
1
0
0
0

将返回 3,因为 4 在三个间隔内减少为 1。

4
4
3
2
1 
0 
0

将返回 0,因为 4 在最近的时间间隔内没有减少。

我写了

declare 
   cursor curr
   is 
          select (YTDOVERDRAFTS - Previous_YTDOVERDRAFTS) colum
          from (select LAG(YTDOVERDRAFTS,1,0) OVER (ORDER BY EFFDATE asc) As Previous_YTDOVERDRAFTS,
           YTDOVERDRAFTS
               from WH_ACCTDEPOSIT
               where ACCTNBR = xxxxxxxxx
               order by effdate desc);
   Counter BINARY_INTEGER :=0;
   readcurr curr%ROWTYPE;
   status INTEGER;
begin 
  open curr; 
  fetch curr into readcurr;
  while readcurr.colum > 0
    loop       
        Counter := Counter + 1;  
        dbms_output.put_line(Counter);
        dbms_output.get_line(Counter, status);
    end loop;
    close curr;
end;

运行,但没有给出应有的输出。我对 dbms_output 语句做错了什么?

【问题讨论】:

  • 您不应该在循环内重新获取curr 吗?
  • 为什么?一旦数据在游标中,我为什么要重新获取它?
  • 您的查询不返回多行吗?每行都需要fetch,不是吗?
  • 不,我的查询只会返回一个整数
  • 对不起,你的代码看了一半,但是如果条件是while readcurr.colum > 0,循环如何结束,而readcurr.column的值在循环期间永远不会改变?

标签: sql database oracle loops plsql


【解决方案1】:

看起来单个查询可以做到这一点,我修改了您的查询,请检查以下内容:

select sum((case when (YTDOVERDRAFTS - Previous_YTDOVERDRAFTS) <> 0 then 1 else 0 end)) non_equal_count
      from (select LAG(YTDOVERDRAFTS,1,0) OVER (ORDER BY EFFDATE asc) As Previous_YTDOVERDRAFTS,
       YTDOVERDRAFTS
           from WH_ACCTDEPOSIT
           where ACCTNBR = xxxxxxxxx);

【讨论】:

  • 我已经完成了项目,我真的只是想让循环正常工作,这样我就可以拍拍自己的后背说“干得好”。
猜你喜欢
  • 2014-05-25
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
相关资源
最近更新 更多