HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to store single result in variable and reuse it in a query (Oracle)?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
resultquerystoresinglereusehowandoraclevariable

Problem

I have a query like

SELECT id FROM xyz WHERE ...;


which has a more or less complex WHERE clause and returns exactly one row with one column (ID). I need this ID for several later queries in a script.
So my goal was to reuse this result in a variable but I don´t come to a solution which works.

Joining this query would not be a good option in this circumstance. So is it possible to tell Oracle to store this single result in a variable and use this variable to build up new queries - explicitly to use in in the conditional clause of other queries?

If so, perhaps somebody could post a simple example - most simple perhaps would be sth. like

SELECT :VARIABLE FROM DUAL

Solution

For Toad, from this answer on SO:


I think this will accomplish what you want. You can declare a bind variable, insert a value into it, and then use it in future statements.

variable l_var varchar2(1);

begin
  select dummy
    into :l_var
    from dual;
end; 

select *
from dual
where dummy = :l_var;

Code Snippets

variable l_var varchar2(1);

begin
  select dummy
    into :l_var
    from dual;
end; 

select *
from dual
where dummy = :l_var;

Context

StackExchange Database Administrators Q#27790, answer score: 2

Revisions (0)

No revisions yet.