在循环外设置一个变量并在循环的每个项目中获取它

Set a variable outside loop and fetch it every item of loop

我的甲骨文版本:Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi

我正在尝试在循环外设置一个变量,并使其值随着循环的每一项而变化。 (就像我们通常在jsp、php...中所做的那样)

create or replace PROCEDURE TEST2 AS 
  -- VARIABLE
    v_variable number; 
    cursor c2 is
    select round(dbms_random.value() * 8) + 1 AS temp_key from dual; -- temp_key is a random value

BEGIN  
    OPEN c2;
    FOR SRC IN (SELECT * FROM TB_MASTER_TEMP2) -- it has many rows
     LOOP
        fetch c2 into v_variable; -- v_variable need to change for every row
        Dbms_Output.Put_Line(SRC.MAS_ENTRY_NM || ', ' ||v_variable); --test
     END LOOP;

END TEST2;

但是结果是

aaa, 8
bbb, 8 --`v_variable` stays the same
...

v_variable 不变。 请更正我的程序。

试试这个

create or replace PROCEDURE TEST2 AS 
-- VARIABLE
v_variable number; 
--cursor c2 is
--select round(dbms_random.value() * 8) + 1 AS temp_key from dual; -- temp_key is a random value

BEGIN  
--OPEN c2;
FOR SRC IN (SELECT * FROM TB_MASTER_TEMP2) -- it has many rows
 LOOP
    --fetch c2 into v_variable; -- v_variable need to change for every row
    select round(dbms_random.value() * 8) + 1 into v_variable from dual; 
    Dbms_Output.Put_Line(SRC.MAS_ENTRY_NM || ', ' ||v_variable); --test
 END LOOP;

END TEST2;

除非有人用它玩过愚蠢的错误,否则 dual 只有一行,因此由 c2 编辑的结果集 return 也只有一行。任何试图获取超出该结果集末尾的内容都只会一遍又一遍地 return 最后(也是唯一)行。

如果你想在循环的每次迭代中检索一个不同的随机值,你需要执行你的SELECT ... FROM dual 每次 你循环,就像@Utsav 的代码一样。

Hello i have slightly tweaked your code. It may help you. Since i dont have workspace with me so plz bear with any syntax errors.

CREATE OR REPLACE PROCEDURE TEST2
AS
  -- VARIABLE
  v_variable NUMBER;
BEGIN
  --  OPEN c2; -- Not required
  FOR SRC IN
  (SELECT t2.*,
    ROUND(dbms_random.value() * 8) + 1 AS temp_key
  FROM TB_MASTER_TEMP2 t2
  ) -- it has many rows
  LOOP
    -- v_variable need to change for every row
    Dbms_Output.Put_Line(SRC.MAS_ENTRY_NM || ', ' ||src.temp_key); --test
  END LOOP;
END TEST2;