Oracle: How to use procedure local variables for “EXECUTE IMMEDIATE” statements in procedures

末鹿安然 提交于 2019-12-20 06:28:27

问题


We have a procedure starting with following code:

CREATE OR REPLACE PROCEDURE get_id
  (id_ IN OUT number, type_ IN number)
IS
  PRAGMA AUTONOMOUS_TRANSACTION;
  local_id number;
BEGIN
  EXECUTE IMMEDIATE 'SELECT SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL into :local_id FROM dual';
  ...

Now if i execute this, the variable "local_id" is not filled with the next sequence value, but with null (although the sequence is raised by 1). If i change this to "... into local_id ..." i get ORA Error 1008 . What is going wrong here?


回答1:


A local variable from the procedure can be bind to the query placeholder with USING [OUT][IN] clause:

  local_id number;
BEGIN
  EXECUTE IMMEDIATE 
       'SELECT SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL into :local_id FROM dual'
     USING OUT local_id;

But for this query you don't need execute immediate, just do:

  local_id number;
BEGIN
  SELECT SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL into local_id FROM dual;

on Oracle 11g you can do it using the assignment operator:

  local_id number;
BEGIN
  local_id := SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL;



回答2:


Change the following line

EXECUTE IMMEDIATE 'SELECT SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL into :local_id FROM dual';

to

EXECUTE IMMEDIATE 'SELECT SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL FROM dual' into local_id;

I have tested this code in Oracle 11g.




回答3:


'SELECT '||RTRIM(V_XUEWC)||' - '||RTRIM(V_XUAC)||' 
                    FROM table 
                    WHERE ACCOUNT_NUM='||RTRIM(V_ACC)||'';

While i am trying assign this result to a variable in execute immediate.. it doesnt return anything. V_XUEWC and V_XUAC are run time variables.



来源:https://stackoverflow.com/questions/20615600/oracle-how-to-use-procedure-local-variables-for-execute-immediate-statements

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