pl sql cursor for循环

时间:2017-04-12 14:21:10

标签: sql oracle plsql

我有两个游标,for循环应根据状态使用游标。

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

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

所以for循环应该使用游标order_hist2是变量status =' COMPLETE' 否则使用order_hist1

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

我不想使用REF游标

1 个答案:

答案 0 :(得分: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;
/