Oracle:如何在过程中将过程局部变量用于“EXECUTE IMMEDIATE”语句

时间:2013-12-16 16:19:47

标签: oracle procedure

我们有一个以下代码开头的程序:

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';
  ...

现在,如果我执行此操作,变量“local_id”不会填充下一个序列值,而是填充为null(尽管序列被提高1)。如果我将其更改为“... into local_id ...”我得到ORA错误1008。这里出了什么问题?

3 个答案:

答案 0 :(得分:3)

过程中的局部变量可以使用USING [OUT][IN]子句绑定到查询占位符:

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

但是对于此查询,您不需要execute immediate,只需执行:

  local_id number;
BEGIN
  SELECT SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL into local_id FROM dual;
在Oracle 11g上,您可以使用赋值运算符来执行此操作:

  local_id number;
BEGIN
  local_id := SYS_LOCAL_ID_SERIAL_SEQ.NEXTVAL;

答案 1 :(得分:1)

更改以下行

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

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

我已经在Oracle 11g中测试了这段代码。

答案 2 :(得分:0)

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

虽然我尝试将此结果分配给执行立即执行的变量..但它不会返回任何内容。 V_XUEWC和V_XUAC是运行时变量。