当我为execute immediate
构建动态SQL语句时,我想使用绑定变量而不是字符串连接。为什么我不能在execute immediate语句中使用绑定变量?
在下面的示例中,我可以使用绑定变量a
,b
和ret
,但是当我尝试绑定为f
,我收到了ORA-06502: PL/SQL: numeric or value error: character to number conversion error
。为什么以及我如何绑定f
?
我正在使用11.2.0.1.0。
create or replace function so4fun (
a in number,
b in number,
f in varchar2
) return number as
decl constant varchar2(32767) :=
'declare a constant number := :a; b constant number := :b;';
stmt varchar2(32676);
ret number;
begin
/* This one works: */
stmt := decl || ' begin :result := ' || f || '; end;';
execute immediate stmt using in a, in b, out ret;
/* But why this one doesn't ?
stmt := decl || ' begin :result := :f; end;';
execute immediate stmt using in a, in b, out ret, in f;
This doesn't work either:
stmt := decl || ' tmp number; begin tmp := :f; :result := tmp; end;';
execute immediate stmt using in a, in b, in f, out ret;
Both are giving me ORA-06502: PL/SQL: numeric or value error: character to
number conversion error */
return ret;
end;
/
show errors
/* expected result when a = 1, b = 2 is 1.5 */
select so4fun(1, 2, '(a + b)/b') from dual;
drop function so4fun;
我选择了Codo的答案,因为我看到他的答案更加全面和紧凑。不过,我也发现Ray Toal的回答很有用,我也可以从他的回答中总结出我的问题的答案。我希望他们两个都有很多赞扬! – user272735