4

我需要有一个条件游标,例如:

  • 如果存在一行(使用WHEN EXISTS或类似的东西),那么我的光标是:
    • CURSOR varCursor IS SELECT 1 a FROM DUAL;
  • 别的
    • CURSOR varCursor IS SELECT 2 a FROM DUAL;

但是看,我不想改变列结果,我想改变整个游标。

下面我举一个更大的例子。

谢谢!


看:

SET serveroutput ON SIZE 900000;
DECLARE
  CURSOR varCursor IS SELECT 1 a FROM DUAL;
  -- CURSOR varCursor IS SELECT 2 a FROM DUAL;
BEGIN
  FOR varRow IN varCursor LOOP
    dbms_output.put_line('row: ' || varRow.a);
  END LOOP;
  dbms_output.put_line('Done.');  
END;
4

2 回答 2

11

除非将其放入一个查询(如托尼建议的那样),因为您想要一个游标结果,您可以这样做(这会将游标切换到您需要的逻辑-> 一种游标解决方案)

DECLARE
  PROCEDURE CURSORCHOICE(ITEM IN NUMBER) IS
      L_REFCUR SYS_REFCURSOR;
    returnNum number;
    BEGIN
        IF NVL(ITEM,0) > 0 THEN
            OPEN L_REFCUR FOR
            SELECT ITEM * level  FROM DUAL 
            CONNECT BY LEVEL < ITEM ;
        ELSE
            OPEN L_REFCUR FOR
            SELECT  ITEM -  LEVEL  FROM DUAL 
            connect by level < -1 * ITEM ;  
        END IF;
        dbms_output.put_line('Results to item ' || item);
      loop
         fetch l_refcur into returnNum;
         exit when l_refcur%notfound;
         dbms_output.put_line(returnNum);
      end loop;
      CLOSE L_REFCUR;

    END ;
BEGIN
CURSORCHOICE(5);
CURSORCHOICE(-5);
end ;
/

Results to item 5
5
10
15
20
Results to item -5
-6
-7
-8
-9
于 2010-10-19T14:16:16.330 回答
7

从字面上看,你可以这样做:

CURSOR varCursor IS SELECT 1 a FROM DUAL WHERE EXISTS (...)
                    UNION
                    SELECT 2 a FROM DUAL WHERE NOT EXISTS (...);

但是,拥有 2 个游标并打开合适的游标会更简单,也可能更有效。

于 2010-10-19T13:59:27.790 回答