简体   繁体   中英

Inserting Data Into Table Using Execute Immediate in Oracle

For example, I have some table "Test" which has one column "my_date" . What I am trying to do is adding record to a table using some variable:

query_date := "SELECT sysdate FROM dual";
EXECUTE IMMEDIATE ('insert into test values query_date');

I need to insert the record to the table in this exact way by constructing string and executing query, however I get error. Is it possible to do so?

You can either get the result of the first query into a (date) variable and then use that:

SELECT sysdate into query_date FROM dual;
insert into test (my_date) values (query_date)
-- or if you really want dynamic SQL, with a bind variable
EXECUTE IMMEDIATE 'insert into test (my_date) values (:query_date)' using query_date;

Or reading your question literally, use the first string as part of the second string by concatenating it:

query_date := "SELECT sysdate FROM dual";
EXECUTE IMMEDIATE 'insert into test (my_date) ' || query_date;

If you printed out the second statement instead of executing it you'd see:

insert into test (my_date) SELECT sysdate FROM dual

... which is valid SQL. This will work if the query_string is more complicated or is itself being constructed dynamically. But if the number of column expressions in the query_string select list also varies, you will have to construct the column list dynamically too, otherwise you'll have too many or too few columns for the insert.

Exactly how you do that depends on how you're constructing the query string - essentially as you add an expression to the query string, you'd also add a column name to a separate list, and end up with:

EXECUTE IMMEDIATE 'insert into test (' || column_list ' ||) ' || query_string);

where column_list is built up as say col1, col2 and query_string as select x.col1, y.col2 from ... .


There isn't an obvious reason to use dynamic SQL in what you've shown. Or, if you are really using sysdate, any need for separate query to get that, as you can just do:

insert into test (my_date) values (sysdate)

... so I assume your real scenario is really more complicated. But note that you don't use the values keyword with an insert ... select ... pattern. You can with a single column and a subquery but it's not a good idea even then, and doesn't work if you have multiple columns in the subquery.

Why you need an EXECUTE IMMEDIATE for Insert statement ? As long as the base table where you are inserting the values remain same we dont need to do EXIMM. Now the query_date ? Just do a traditional looping or variable thing.

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