【问题标题】:ORA-06502 while dbms_sql.execute(<anonymous block>) with out-bindingORA-06502 而 dbms_sql.execute(<anonymous block>) 具有出绑定
【发布时间】:2021-09-08 00:28:24
【问题描述】:

我在通过 dbms_sql 使用绑定变量(输入和输出)执行动态 SQL 时遇到了一些麻烦。 我总是得到 ORA-06502 但无法得到原因。 到目前为止,我可以减少 SQL-sn-p 以知道 out 参数发生错误。

declare
  l_cur_id NUMBER;
  l_sql    VARCHAR2(100) := 'begin :1 := ''test''; end;';
  l_res    VARCHAR2(100);
  l_dbms   NUMBER;
begin
  l_cur_id := dbms_sql.open_cursor;
  dbms_sql.parse(l_cur_id, l_sql, dbms_sql.native);
  dbms_sql.bind_variable(l_cur_id, '1', l_res);
  l_dbms := dbms_sql.execute(l_cur_id); -- ORA here
  dbms_sql.close_cursor(l_cur_id);
exception
  when others then
    dbms_sql.close_cursor(l_cur_id);
    raise;
end;
/

内参数工作正常。 我正在使用 Oracle Database 12 Enterprise Edition Release 12.1.0.2.0

我必须以其他方式配置 out-parameter 吗? 感谢您的帮助。

【问题讨论】:

    标签: oracle plsql oracle12c dynamic-sql


    【解决方案1】:

    您尚未指定绑定变量的大小。默认情况下,它使用变量的当前长度; from the documentation:

    Parameter Description
    out_value_size Maximum expected OUT value size, in bytes, for the VARCHAR2, RAW, CHAR OUT or IN/OUT variable. If no size is given, then the length of the current value is used. This parameter must be specified if the value parameter is not initialized.

    由于该变量默认初始化为 null,因此该长度为零;这与说它未初始化相同。因此,当它尝试将四个字符 'test' 分配给零字符变量时会出错。

    您还可以need to call dbms_sql.variable_value 来检索出绑定变量值。

    如果你用一个值至少初始化l_res,只要你可以在动态块内分配任何东西,它就会起作用:

    declare
      ...
      l_res    VARCHAR2(100) := 'xxxx';
      ...
    begin
      ...
      dbms_sql.bind_variable(l_cur_id, '1', l_res);
      l_dbms := dbms_sql.execute(l_cur_id);
      dbms_sql.variable_value(l_cur_id, '1', l_res);
      ...
    end;
    /
    

    但这显然是理想的,因为实际上您需要提供一个 100 个字符长的值,并且如果以后长度发生变化,请记住对其进行调整;所以改为在绑定调用中指定长度:

    declare
      ...
      l_res    VARCHAR2(100);
      ...
    begin
      ...
      dbms_sql.bind_variable(l_cur_id, '1', l_res, 100);
      l_dbms := dbms_sql.execute(l_cur_id);
      dbms_sql.variable_value(l_cur_id, '1', l_res);
      ...
    end;
    /
    

    db<>fiddle

    【讨论】:

    • 嗨,亚历克斯,我都试过了。该错误不再发生,谢谢:) 但在这两种情况下,l_res' 的值都不会改变(所以它是null'xxxx')。
    • @StefanWarminski - 你错过了 variable_value 通话 - 更新了答案和 dbfiddle。
    猜你喜欢
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2015-06-11
    相关资源
    最近更新 更多