Skip to Main Content
  • Questions
  • Can I Assign return value of Stored Function to DEFINE in SQL Script.

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question, Mukesk .

Asked: May 02, 2000 - 1:21 pm UTC

Last updated: May 02, 2000 - 1:21 pm UTC

Version:

Viewed 1000+ times

You Asked

Can I Assign return value of Stored
Function to DEFINE in SQL Script.

For e:g
ret := my_fun(dummy)
DEFINE YYY = ret ?? Is it possible ?
Now in SQl Script I have to use this RET value as the Value of DEFINE .



and Tom said...



there are 2 ways to do this, both require you do something like:

ops$tkyte@8i> column x new_val my_x

that says "when I run a query that selects a column named X put the value of the last row fetched into a define variable called MY_X".

Now, if I have a function I can "select" (eg: it does not write to the database state -- no inserts/updates/deletes) I can simply:


ops$tkyte@8i> create or replace function foo( a in number ) return number
2 as
3 begin
4 return a*2;
5 end;
6 /
Function created.

ops$tkyte@8i> select foo(10) X from dual;

X
----------
20

ops$tkyte@8i>
ops$tkyte@8i> select &my_x from dual;
old 1: select &my_x from dual
new 1: select 20 from dual

20
----------
20




select that function from dual to run it and get the value into the define variable. If I cannot select foo() from dual -- I can still do this using a bind variable:

ops$tkyte@8i> variable bind_var number
ops$tkyte@8i> exec :bind_var := foo( 22 )

PL/SQL procedure successfully completed.

ops$tkyte@8i> select :bind_var X from dual;

X
----------
44

ops$tkyte@8i>
ops$tkyte@8i> select &my_x from dual;
old 1: select &my_x from dual
new 1: select 44 from dual

44
----------
44


So I can always select BIND_VARIABLE "X" from dual; and that'll do it for me.





Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Setting a user variable from a bind variable

David McCormack, May 13, 2009 - 2:44 am UTC

Your article was incredibly useful as I have been banging my head on this for quite a while. I have attached my simple example of how I used this "feature" to set a user variable from a bind variable. I don't guarantee it is 100% as you are the guru not me.

SET SERVEROUTPUT ON

define userVar = ''
variable bindVar VARCHAR2(15);

declare

begin

if (1 = 1) then
DBMS_OUTPUT.PUT_LINE('In 1 = 1');
:bindVar := 'here';
else
DBMS_OUTPUT.PUT_LINE('not in 1 = 1');
:bindVar := 'there';
end if;
end;
/

column X new_val userVar
select :bindVar X from dual;

define userVar

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library