Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Statement inside a procedure in Oracle

sorry for asking this question but it's because none of the answers given before are enough for me to understand. I want to write a stored procedure that returns all the columns in a table.As an ad hod query I just write

SELECT * FROM EMPLOYEES

but here, I get an error which prompts me to provide INTO clause which I don't understand why and how.Could someone explain how would I do that both in the above case and when I want to return just one column values(multiple rows).

like image 314
Mikayil Abdullayev Avatar asked May 17 '11 10:05

Mikayil Abdullayev


1 Answers

People with a SQL Server background are used to writing stored procedures that return whole query results and so try to write PL/SQL procedures something like this:

procedure get_emps is
begin
    -- this will NOT work!
    select * from emp;
end;

Unfortunately it's not that simple. Probably the nearest equivalent in PL/SQL is a function returning a ref cursor:

function get_emps return sys_refcursor is
    rc sys_refcursor;
begin
    open rc for
        select * from emp;
    return rc;
end;

You could call this from a calling program like this:

declare
    cur sys_refcursor;
    emp_rec emp%rowtype;
begin
    cur := get_emps;
    loop
        fetch cur into emp_rec;
        exit when cur%notfound;
    end loop;
    close cur;
end;

or in SQL Plus you could do:

var rc refcursor
:rc := get_emps;
print rc
like image 58
Tony Andrews Avatar answered Oct 14 '22 19:10

Tony Andrews