EXECUTE IMMEDIATE using column names from dual

1.1k Views Asked by At

In my package, I have a procedure like this:

PROCEDURE sp_directUpdate(COL C%ROWTYPE) IS
BEGIN

   EXECUTE IMMEDIATE 'INSERT INTO T1(SELECT COL.F0, COL.F1 FROM DUAL)';

END IF;

END;

for table T1, I need only two columns from dual: COL.F0 & COL.F1.

When I execute this statement, I get "COL"."F1" is an invalid identifier.

In the same procedure, for inserting values into table T2, my statement might look like this:

 EXECUTE IMMEDIATE 'INSERT INTO T2(SELECT COL.F0, COL.F1, COL.F4 FROM 
  DUAL)';

I will run into a similar problem again. Can you suggest me a way to solve this problem without using INTO clause?

1

There are 1 best solutions below

4
Jeffrey Kemp On

Firstly, the INSERT AS SELECT syntax does not have parentheses () around the query.

If you use EXECUTE IMMEDIATE, the statement is a string executed outside the context of the procedure so it cannot refer to the parameters. You would need to supply them as bind variables, e.g.:

PROCEDURE sp_directUpdate(COL C%ROWTYPE) IS
BEGIN

   EXECUTE IMMEDIATE 'INSERT INTO T1 AS SELECT :1, :2 FROM DUAL'
     USING COL.F0, COL.F1;

END;

However, I would question whether you need to use dynamic SQL at all - you can run the insert directly:

PROCEDURE sp_directUpdate(COL C%ROWTYPE) IS
BEGIN

   INSERT INTO T1 AS SELECT COL.F0, COL.F1 FROM DUAL;

END;

In addition, in this case you could use a single row insert statement instead of running an "insert as select":

PROCEDURE sp_directUpdate(COL C%ROWTYPE) IS
BEGIN

   INSERT INTO T1 VALUES (COL.F0, COL.F1);

END;

P.S. if this is supposed to do an insert, why is the procedure called "directUpdate"? :)