簡體   English   中英

如何將游標值傳遞給變量?

[英]How to pass cursor values into variable?

我正在嘗試使用游標從table1的兩個column1,column2中讀取值。 然后,我想將這些值傳遞給另一個游標或select into語句,以便我的PL / Sql腳本將使用這兩列的值從另一個名為table2的表中獲取數據

這可能嗎? 而做這種事情的最好,最快的方法是什么?

謝謝 :)

是的,可以將游標值傳遞給變量。 只需使用將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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM