Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally define a Cursor

I have a Procedure in Oracle that takes a varchar2 paramater. Based on the value of that parameter, I need to define a cursor. The cursor will operate on different tables based on the value of the parameter.

I wanted to do something like below but it throws an error in the CURSOR definition piece of code. Any ideas?

PROCEDURE GET_RECORDS(v_action IN VARCHAR2)
IS
CURSOR get_records
IS
       IF(v_action = 'DO THIS') THEN
           SELECT * from <THIS>;
       ELSE
           SELECT * from <THAT>;
       END IF;
BEGIN
       OPEN get_records;

       FETCH get_records
       INTO v_thing;

       v_loop := 0;
       WHILE get_records%FOUND
       LOOP

           FETCH get_records
           INTO v_thing;

       END LOOP;
       CLOSE get_records;
END;
like image 539
MikeTWebb Avatar asked Feb 01 '11 15:02

MikeTWebb


People also ask

How do you define a cursor?

1) A cursor is the position indicator on a computer display screen where a user can enter text. In an operating system with a graphical user interface (GUI), the cursor is also a visible and moving pointer that the user controls with a mouse, touch pad, or similar input device.

How do you set a cursor to a variable?

To create a cursor variable, either declare a variable of the predefined type SYS_REFCURSOR or define a REF CURSOR type and then declare a variable of that type. You cannot use a cursor variable in a cursor FOR LOOP statement. You cannot declare a cursor variable in a package specification.

What is the right syntax to declare a cursor?

Declare a cursor In this syntax: First, specify the name of the cursor after the CURSOR keyword. Second, define a query to fetch data after the IS keyword.

Can we declare cursor in package specification?

The package body contains the implementation of every cursor and subprogram declared in the package spec. Subprograms defined in a package body are accessible outside the package only if their specs also appear in the package spec.


1 Answers

you will need a REF CURSOR and open it conditionaly, for example:

SQL> CREATE OR REPLACE PROCEDURE GET_RECORDS(v_action IN VARCHAR2) IS
  2     v_thing     VARCHAR2(10);
  3     get_records SYS_REFCURSOR;
  4  BEGIN
  5     IF (v_action = 'DO THIS') THEN
  6        OPEN get_records FOR
  7           SELECT 1 FROM dual;
  8     ELSE
  9        OPEN get_records FOR
 10           SELECT 2 FROM dual;
 11     END IF;
 12  
 13     LOOP
 14        FETCH get_records INTO v_thing;
 15        EXIT WHEN get_records%NOTFOUND;
 16        /* do things */
 17        dbms_output.put_line(v_thing);
 18     END LOOP;
 19     CLOSE get_records;
 20  END;
 21  /

Procedure created

SQL> exec get_records ('DO THIS');
1

PL/SQL procedure successfully completed

SQL> exec get_records ('DO THAT');
2

PL/SQL procedure successfully completed
like image 89
Vincent Malgrat Avatar answered Oct 20 '22 19:10

Vincent Malgrat