如何将游标值传递给变量?

时间:2014-02-11 06:28:59

标签: oracle

我正在尝试使用cursor从table1中的两个column1,column2读取值。然后我想将这些值传递给另一个游标或选择into语句 所以我的PL / Sql脚本将使用这两列的值来从另一个名为table2

的表中获取数据

这可能吗?做这样的事情的最好和最快的方法是什么?

谢谢:)

1 个答案:

答案 0 :(得分:0)

是的,可以将游标值传递给变量。只需使用fetch <cursor_name> into <variable_list>从游标中再获取一行。之后,您可以使用某些where语句的select into子句中的变量。如,

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;

如果使用隐式游标,则更简单:

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;

在这些示例中,使用子查询

更有效
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;