Oracle: What does 'execute immediate' mean?

爱⌒轻易说出口 提交于 2021-01-27 05:07:24

问题


What is the significance of execute immediate in PL/SQL when used with DML and DDL statements? Does execute immediate implicitly commit to a database like DDL statements do ?

The following is an example I have encountered:

SELECT 'TRUNCATE TABLE BD_BIDS_APPR_DET' INTO V_SQL1 FROM DUAL;
EXECUTE IMMEDIATE V_SQL1;

SELECT 'TRUNCATE TABLE BD_BIDS_SYS_DET' INTO V_SQL1 FROM DUAL;
EXECUTE IMMEDIATE V_SQL1;

SELECT 'TRUNCATE TABLE BD_BIDS_EXT_DET' INTO V_SQL1 FROM DUAL;
EXECUTE IMMEDIATE V_SQL1;

回答1:


It is for running native dynamic SQL.

For DML you'd use it when running statements that you don't have available at compile time, e.g. if the column list is based on a selection from the user.

In your case it's being used because DDL cannot be run as static SQL from within PL/SQL. Only certain query, DML and TCL commands are valid. Anything else has to be treated as dynamic.

I'd say it's rare to need to use DDL from a PL/SQL block. TRUNCATE might be reasonable; if you find anything creating or dropping objects on the fly then that might be more of a concern as it can suggest a suboptimal data model.

EXECUTE IMMEDIATE itself does not automatically commit; but if you execute DDL then that will behave the same as if you ran it outside PL/SQL, so it will commit in your case, yes.

Incidentally, I'm not sure why your code is using an intermediate variable to hold the statement; that's useful if you want to display what it's going to run maybe, but you don't seem to be doing that. What you have could be done as:

EXECUTE IMMEDIATE 'TRUNCATE TABLE BD_BIDS_EXT_DET';

i.e. without using V_SQL_1 at all.




回答2:


It provides end-to-end support when executing a dynamic SQL statement or an anonymous PL/SQL block. It substitutes the unknown values, executes the statement, returns the data, and then releases the resources.

EXECUTE IMMEDIATE [dynamic SQL string statement without terminator]

 [INTO {define_variable     [, define_variable] ... | record}]

 [USING [IN|OUT|IN OUT] bind_argument [, [IN|OUT|IN OUT] bind_arguments] ];

define_variable is a PL/SQL variable or record that captures the result set of the SELECT query

Bind arguments are the actual values or local variables which would replace the bind variables in the SQL string statement.



来源:https://stackoverflow.com/questions/18375990/oracle-what-does-execute-immediate-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!