Search code examples
oracleplsqloracle8i

Oracle 8i dynamic SQL error on subselects in pl/sql blocks


I wrote an Oracle function (for 8i) to fetch rows affected by a DML statement, emulating the behavior of RETURNING * from PostgreSQL. A typical function call looks like:

SELECT tablename_dml('UPDATE tablename SET foo = ''bar''') FROM dual;

The function is created automatically for each table and uses Dynamic SQL to execute a query passed as an argument. Moreover, a statement that executes the query dynamically is also wrapped in a BEGIN .. END block:

EXECUTE IMMEDIATE 'BEGIN'||query||' RETURNING col1, col2 BULK COLLECT INTO :1, :2;END;' USING OUT col1_t, col2_t;

The reason behind this perculiar construction is that it seems to be the only way to get values from the DML statement that affects multiple rows. Both col1_t and col2_t are declared as collections of the types corresponding to the table columns.

Finally, to the problem. When the query passed contains a subselect, execution of the function produces a syntax error. Below is a simpe example to illustrate this:

CREATE TABLE xy(id number, name varchar2(80));
CREATE OR REPLACE FUNCTION xy_fn(query VARCHAR2) RETURN NUMBER IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
EXECUTE IMMEDIATE 'BEGIN '||query||'; END;';
ROLLBACK;
RETURN 5;
END;
SELECT xy_fn('update xy set id = id + (SELECT min(id) FROM xy)') FROM DUAL;

The last statement produces the following error: (the SELECT that is mentioned there is the SELECT min(id))

ORA-06550: line 1, column 32: PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + mod not null others avg count current exists max min prior sql stddev sum variance execute forall time timestamp interval date

This problem occurs on 8i (8.1.6), but not 10g. If BEGIN .. END blocks are removed - the problem disappears. If a subselect in a query is replaced with something else, i.e. a constant, the problem disappears.

Unfortunately, I'm stuck with 8i and removing BEGIN .. END is not an option (see the explanation above).

Is there a specific Oracle 8i limitation in play here? Is it possible to overcome it with dynamic SQL?


Solution

  • Not sure why you need to do all this work. Oracle 8i supported RETURNING INTO with bulk collection. Find out more

    So you should just be able to execute this statement in non-dynamic SQL. Something like this:

    UPDATE tablename 
    SET foo = 'bar' 
    returning  col1, col2 bulk collect into col1_t, col2_t;