Question

I have used this type of functionality before but is MSSQL but can't get it to work for Oracle, any tips?

DECLARE
    MY_TBL NUMBER := 1;

BEGIN

    IF(MY_TBL > 0) THEN
        SELECT * FROM MY_TBL ORDER BY MY_TBL_ID DESC;
    END IF;
END;

What I would like to have is a flag variable set to zero or one, if one display the results, if zero skip. This is just a simple script to have all my tables and select statements in one script ans flag the ones I need to see the results for. So if I have 5 tables I would use the ELSIF function to add more like this

DECLARE
    MY_TBL1 NUMBER := 1;
    MY_TBL2 NUMBER := 1;

BEGIN

    IF(MY_TBL1 > 0) THEN
        SELECT * FROM MY_TBL1 ORDER BY MY_TBL1_ID DESC;
    ELSIF(MY_TBL2 > 0) THEN
        SELECT * FROM MY_TBL2 ORDER BY MY_TBL2_ID DESC;
    END IF;
END;

and so on. Thanks for any help on this, --Phill

EDIT:

Here is what I have:

VAR result_set REFCURSOR

DECLARE
   my_tbl_1 NUMBER := 1;
   my_tbl_2 NUMBER := 0;
   my_tbl_3 NUMBER := 0;
BEGIN
   IF (my_tbl_1 > 0)
   THEN
      BEGIN
         OPEN :result_set FOR
            SELECT   *
                FROM my_tbl_1
            ORDER BY my_tbl_1_id DESC;
      END;
   ELSIF (my_tbl_2 > 0)
   THEN
      BEGIN
         OPEN :result_set FOR
            SELECT   *
                FROM my_tbl_2
            ORDER BY my_tbl_2_id DESC;
      END;
   ELSIF (my_tbl_3 > 0)
   THEN
      BEGIN
         OPEN :result_set FOR
            SELECT   *
                FROM my_tbl_3
            ORDER BY my_tbl_3_id DESC;
      END;
   END IF;
END;

PRINT result_set
Was it helpful?

Solution

Oracle cannot return resultsets from a stored procedure as SQL Server does.

Declare cliend side cursor variables and return to them:

To display a cursor in SQL*Plus:

VAR cur1 REFCURSOR

DECLARE
        MY_TBL1 NUMBER := 1;
        MY_TBL2 NUMBER := 1;

BEGIN
        IF(MY_TBL1 > 0) THEN
        BEGIN
                OPEN :cur1
                FOR
                SELECT  *
                FROM    MY_TBL1
                ORDER BY
                        MY_TBL1_ID DESC;
        END;
        ELSIF (MY_TBL2 > 0) THEN
        BEGIN
                OPEN :cur1
                FOR
                SELECT  *
                FROM    MY_TBL2
                ORDER   BY
                        MY_TBL2_ID DESC;
        END;
        END IF;
END;
/

PRINT cur
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top