2017-04-12 75 views
1

我有两个游标for循环应该使用基于状态的游标。pl sql游标在循环中

CURSOR order_hist1 IS 
    SELECT id, ordernum, address FROM order_hist; 

CURSOR order_hist2 IS 
    SELECT id, ordernum, address FROM order_hist_complete; 

所以循环应当使用光标order_hist2是可变的状态= '完成' 使用别的order_hist1

FOR aDistinctLine in --  LOOP 
    -- 300 lines code in this loop 
END LOOP; 

我不想o使用REF游标

+0

似乎已经回答了[链接](http://stackoverflow.com/questions/4864404/conditionally-define-a-cursor-in-oracle) –

+0

的[有条件地定义Oracle中的游标可能的复制](http://stackoverflow.com/questions/4864404/conditionally-define-a-cursor-in-oracle) –

回答

1

您可以使用隐for循环:

  • 对于您的情况,它看起来适合将两个游标更改为单个Ë之一,采用UNIONUNION ALL如果你需要处理的重复,或性能方面的原因),就像如下:

FOR aDistinctLine in (
    -- first cursor: status <> COMPLETE 
    SELECT id, ordernum, address FROM order_hist 
    WHERE status <> 'COMPLETE' 
    UNION 
    SELECT id, ordernum, address FROM order_hist_complete 
    WHERE status = 'COMPLETE' 
) LOOP 

-- do things with 
--  aDistinctLine.id, 
--  aDistinctLine.ordernum, 
--  aDistinctLine.address 

END LOOP; 

那么最好有status看起来像一个局部变量,例如称它为l_status;我不得不说服自己可以在隐式for循环中使用plsql变量......我今天学到了一些东西!

declare 
    l_status varchar2(8) := 'COMPLETE'; 
begin 
    for x in (select 'realy?' val from dual where l_status = 'COMPLETE') 
    loop 
    dbms_output.put_line(x.val); 
    end loop; 

    l_status := 'graby'; 
    for x in (select 'here: not complete' val from dual where l_status <> 'COMPLETE') 
    loop 
    dbms_output.put_line(x.val); 
    end loop; 
end; 
/
+0

另外,我认为,OP可能有一个表,说'订单',它将存储变量'状态= complete'。 –

+1

@SudiptaMondal - 这个问题说'status'是一个变量(尽管这确实假设表中的游标并没有一个具有该名称的列,但你只能继续通过OP所告诉你的内容)。而2000线呢?如果你愿意,你仍然可以用这种方式使用单个显式游标 - 你甚至可以通过状态变量作为正式参数... –

+0

是的状态不是这两个表的一部分:-( – user565992