tags:

views:

40

answers:

1

Can I change the value of a variable by using a select into with the variable's original value as part of the where clause in the select statement?

EI would the following code work as expected:

declare
v_id number;
v_table number; --set elsewhere in code to either 1 or 2
begin
  select id into v_id from table_1 where name = 'John Smith';
  if(v_table = 2) then
    select id into v_id from table_2 where fk_id = v_id;
  end if;
end;
+2  A: 

Should work. Have you tried it? Any issues?

After parsing your select statements should have bind variables where your v_id is. The substitution is made when the statement is actually executed.

Edit: Unless you're sticking constants into your queries, Oracle will always parse them into statements with bind variables - it enables the DBMS to reuse the same basic query with multiple values without reparsing the statement - a huge performance gain. The whole idea of a bind variable is runtime substitution of values into a parsed query. Think of it this way: in order to process a query, all of the values need to be known. You send them to the engine, Oracle does it's work, and returns a result. It's a serial process with no way for the output value to step on the input one.

DCookie
It did work. However, my concern is this: is this always going to work?
David Oneill
IE do you *know* that it will use bind variables and substitute after the statement is done executing? I can't really afford to have it only work some of the time...
David Oneill
I guess if it lets you sleep at night, use two different variables then ;-)
DCookie
It will work. Basically it does the BIND of the variable to the statement, then it executes the statement, which will return the value. Only caveat is that, if the statement fails (no data found, too many rows etc), I wouldn't rely on what value might be in the variable.
Gary
As Gary said, it will always work as expected. If the statement fails, it'll raise an exception, so it won't get to the 2nd select.
Jeffrey Kemp