【问题标题】:How to pass cursor values into variable?如何将游标值传递给变量?
【发布时间】:2014-02-11 06:28:59
【问题描述】:

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

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

谢谢:)

【问题讨论】:

  • refcursors 是为了这个,但我总是猜想,一个子查询可以做同样的事情。你也可以考虑使用嵌套表。(pl sql table)。您可以将嵌套表转换为实际表并在查询中使用。

标签: oracle


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多