I've written the following PL/SQL to dynamically execute a formula given to me as a string. The final output from the formula should return 19
, which I was hoping would be returned into my o_
variable.
The code actually runs without error, but doesn't give me the result I was expecting. Am I using the DBMS_SQL
package correctly?
Please note that a complicating factor to this problem, is that I don't know how many bind-variables will be included in the input string (or formula). Therefore, I can't use the EXECUTE IMMEDIATE
strategy of executing dynamic PL/SQL, because EXECUTE IMMEDIATE
assumes that you know ahead of time how many variables need binding.
Am I approaching the problem in the correct way? Is there a better way of doing this?
DECLARE
cur_ INTEGER;
r_ NUMBER;
str_ VARCHAR2(2000) := 'BEGIN :out := :x * 3 + :y; END;';
x_ NUMBER := 3;
y_ NUMBER := 10;
o_ NUMBER;
BEGIN
cur_ := Dbms_SQL.open_cursor;
Dbms_SQL.Parse (cur_, str_, Dbms_SQL.Native);
Dbms_SQL.Bind_Variable (cur_, ':out', o_);
Dbms_SQL.Bind_Variable (cur_, ':x', x_);
Dbms_SQL.Bind_Variable (cur_, ':y', y_);
r_ := Dbms_SQL.Execute (cur_);
Dbms_SQL.Close_Cursor (cur_);
Dbms_Output.Put_Line ('Your variables: ' || x_ || ', ' || y_ || ', and out: ' || o_ || ', and R: ' || r_);
END;