1

I have the following for loop

for i in (
select * from employees)

loop
--code
end loop;

Is it possible to assign the select statement in a variable like

sql_stat := 'select * from employees';

and in loop

for i in (
    sql_stat)
loop

When I tried the above I am getting error "Encountered the symbol loop"

What is the correct way of doing this if I want to assign the select statement in a variable.

Thanks

4

2 回答 2

4

You can use ref cursors to get result you want. Here is an example.

declare
      type t_cursor is ref cursor;
      c_cursor t_cursor;
      l_sql varchar2(123);
      l_var number;
   begin
     l_sql := 'select count(*) from T1';  -- your query goes here
     open c_cursor for l_sql;
     loop
       fetch c_cursor 
        into l_var;-- variable(s) of appropriate datatype you want to fetch data into
       exit When c_cursor%notfound;
       -- any work for processing fetched data goes here
     end loop;  
  end; 
于 2012-09-18T10:30:42.413 回答
0

Why do you want to store the select statement in a variable? One would only do this if part of the query is variable. For example the table_name.

Usually the query is static and the normal way of accessing the results of a query row for row is to use a cursor for loop such as this:

declare
   cursor c is 
     select column1,column2 
     from table;
begin
  for r in c loop
     dbms_output.put_line(r.column1||' '||r.column2);
  end loop;
end;
于 2012-09-18T11:51:10.070 回答