2015-11-17 68 views
0
的每一個項目

我的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不會改變。 請修復我的程序。

回答

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

除非有人扮演愚蠢的傢伙吧,dual有單排,所以通過c2返回的結果集也有一行。任何試圖超出結果集的結尾的操作都會簡單地返回最後一行(也是唯一一行)。

如果你想檢索循環的每個迭代不同隨機值,則需要執行你的SELECT ... FROM dual每次你循環,如@ UTSAV的代碼。

+0

現在我明白了。我認爲每次調用'fetch'時,都會執行'select'並將其提取到變量中。 – Deckard

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;