Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a single column value and store it in variable oracle sql

Tags:

sql

oracle

I want to grab a particular column value a.id and store it into a variable v_id. Then use this value to pass into a stored procedure.

DECLARE v_id a.id%TYPE;
BEGIN
SELECT id  into v_id from a where a.name='test' and rownum <2 order by id desc;
Print v_id;
doSomething(v_id);
END;
/

I'm getting this error in Oracle SQL Developer:

Error report: ORA-06550: line 3, column 7: PLS-00103: Encountered the symbol "V_ID" when expecting one of the following:

:= . ( @ % ; The symbol ":=" was substituted for "V_ID" to continue. 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action:

like image 854
Th3sandm4n Avatar asked Mar 29 '12 22:03

Th3sandm4n


People also ask

How do you store a value in a variable in SQL query?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

What clause must be added to a SELECT statement to store the fetch result in a variable in a PL SQL block?

A user-defined or %ROWTYPE record into which rows of values are fetched. For each select_item value returned by the query, there must be a corresponding, type-compatible field in the record. Anything that can follow the FROM clause in a SQL SELECT statement (except the SAMPLE clause).


1 Answers

If you want to use rownum and order by you have to put the order by in a sub-query. There is no other way to guarantee that you get the correct value.

It's also good practice to deal with the possibility that there may not be an id that matches your query. I've added an additional begin... end; block to deal with this.

declare
   v_id a.id%type;
begin

   begin
      select id into v_id 
        from ( select id
                 from a 
                 where name = 'test' 
                 order by id desc )
       where rownum < 2 
             ;
    exception when no_data_found then
      v_id := null;
    end;

   dbms_output.put_line(v_id);
   doSomething(v_id);

end;
/

As @raukh noted (whilst I was writing this!) the problem is print, which should be dbms_output.put_line()

like image 104
Ben Avatar answered Oct 26 '22 12:10

Ben