“For 循环”Oracle PL/SQL 中的迭代计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30882928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:53:42  来源:igfitidea点击:

Iteration Count in "For Loop" Oracle PL/SQL

oracleloopsplsqlcountiteration

提问by Prabha Christ

Write PLSQL block to display the ODD numbers and total odd numbers in given number? Ex: If given number is 3, display as below 1 is odd number 3 is odd number Total 2 odd numbers in 3

编写PLSQL块以显示给定数字中的奇数和总奇数?例如:如果给定的数字是 3,则显示如下 1 是奇数 3 是奇数 3 中共有 2 个奇数

CREATE OR REPLACE PROCEDURE odd_num(p_num NUMBER ) 
   IS s_num NUMBER;
BEGIN 
   FOR i_num IN 1..p_num  
      LOOP   
         IF mod(i_num,2) = 1 
         THEN     
            dbms_output.put_line(i_num ||' is Odd Number');  
         END IF; 
      END LOOP;  
   dbms_output.put_line('Total '|| s_num ||' Odd Numbers in '||p_num);
END;

回答by Lalit Kumar B

You just need to initialize and assign the counterto s_num. Just add the following inside the IFblock:

您只需要初始化并将计数器分配给s_num. 只需在IF块中添加以下内容:

s_num := s_num +1;

For example,

例如,

SQL> CREATE OR REPLACE PROCEDURE odd_num(p_num NUMBER )
  2  IS
  3  s_num NUMBER;
  4  BEGIN
  5     s_num :=0;
  6     FOR i_num IN 1..p_num
  7        LOOP
  8           IF mod(i_num,2) = 1
  9           THEN
 10              -- Increment the counter once for each iteration
 11              s_num := s_num +1;
 12              dbms_output.put_line(i_num ||' is Odd Number');
 13           END IF;
 14        END LOOP;
 15     dbms_output.put_line('Total '|| s_num ||' Odd Numbers in '||p_num);
 16  END;
 17  /

Procedure created.

SQL> sho err
No errors.

Let's executethe procedure:

让我们执行过程

SQL> SET SERVEROUTPUT ON
SQL> EXEC odd_num(5);
1 is Odd Number
3 is Odd Number
5 is Odd Number
Total 3 Odd Numbers in 5

PL/SQL procedure successfully completed.

SQL>