简体   繁体   中英

EXECUTE IMMEDIATE using column names from dual

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?

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, eg:

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM