简体   繁体   中英

How to pass cursor values into variable?

I am trying to read values from two column1, column2 from table1 using cursor. Then I want to pass these values to another cursor or select into statement so my PL/Sql script will use the values of these two columns to get data from another table called table2

Is this possible? And what's the best and fastest way to do something like that?

Thanks :)

Yes, it's possible to pass cursor values into variables. Just use fetch <cursor_name> into <variable_list> to get one more row from a cursor. After that you can use the variables in where clause of some select into statement. Eg,

declare
  cursor c1 is select col1, col2 from table1;
  l_col1 table1.col1%type;
  l_col2 table1.col2%type;  
  l_col3 table2.col3%type;  
begin
  open c1;
  loop
    fetch c1 into l_col1, l_col2;
    exit when c1%notfound;


    select col3
      into l_col3
      from table2 t
     where t.col1 = l_col1  --Assuming there is exactly one row in table2
       and t.col2 = l_col2; --satisfying these conditions

  end loop;
  close c1;
end;

If you use an implicit cursor, then it's even simpler:

declare
  l_col3 table2.col3%type;  
begin
  for i in (select col1, col2 from table1)
  loop

    select col3
      into l_col3
      from table2 t
     where t.col1 = i.col1  --Assuming there is exactly one row in table2
       and t.col2 = i.col2; --satisfying these conditions      

  end loop;
end;

In these examples, it's more efficient to use a subquery

begin
  for i in (select t1.col1
                 , t1.col2
                 , (select t2.col3
                      from table2 t2
                     where t2.col1 = t1.col1 --Assuming there is atmost one such
                       and t2.col2 = t1.col2 --row in table2
                   ) col3
              from table1 t1)
  loop
    ...        
  end loop;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM