设置变量外部循环并获取每个循环项

时间:2015-11-17 07:48:48

标签: oracle stored-procedures oracle10g

我的oracle版本: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没有变化。 请遵守我的程序。

3 个答案:

答案 0 :(得分:2)

除非某人玩过愚蠢的玩家,dual只有一行,所以c2返回的结果集也只有一行。任何超过该结果集末尾的尝试都会一次又一次地返回最后一行(也是唯一一行)。

如果要在循环的每次迭代中检索不同的随机值,则需要每次循环执行SELECT ... FROM dual ,如@ Utsav的代码。

答案 1 :(得分:1)

试试这个

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;

答案 2 :(得分:1)

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;