暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 如何在exexute立即字符串内部传递一个bind变量?

askTom 2018-04-06
250

问题描述

这里已经多次讨论了在动态SQL语句中使用绑定变量的好处。

我有这样的动态SQl语句,其中 “id” 是pls_integer:

---- ENSURE THAT BULK PROCESSING IS DISABLED ----
              begin
                execute immediate 'begin
                                     if ... then
                                       ...;
                                       log#.warn('' some text ''''' || || id || || '''''more text'');
                                     end if;
                                   end;';
              exception
                when others then debug('some error');
              end;


这会导致过多的内存使用。

如何将id替换为bind变量以使其最小化?

begin
  execute immediate 'begin
                       log#.warn(''- :1 -'');
                     end;'
  using 'Whoa!';
end;


但这在SQL Developer中给出了以下错误

Error starting at line : 1 in command -
begin
  execute immediate 'begin
                       log#.warn(''- :1 -'');
                     end;'
  using 'Whoa!';
end;
Error report -
ORA-01006: bind variable does not exist
ORA-06512: at line 2
01006. 00000 -  "bind variable does not exist"
*Cause:    
*Action:


我也试过了

begin
  execute immediate 'declare
                       l_id pls_integer := :1;
                     begin
                       log#.warn(''- ''''' || l_id || ''''' -'');
                     end;'
  using 'Whoa!';
end;


但这给了

Error starting at line : 1 in command -
begin
  execute immediate 'declare
                       l_id pls_integer := :1;
                     begin
                       log#.warn(''- ''''' || l_id || ''''' -'');
                     end;'
  using 'Whoa!';
end;
Error report -
ORA-06550: line 5, column 47:
PLS-00201: identifier 'L_ID' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:


任何帮助将不胜感激!

专家解答

诀窍是你需要在你的字符串中连接绑定变量。

使用q运算符可以更轻松地确保正确排列报价:

begin

execute immediate q'!begin
dbms_output.put_line('- ' || :1 || '-');
end;!'
using 'Whoa!';

end;
/

- Whoa!-


PL/SQL procedure successfully completed.

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论