2014-02-11 24 views
0

我想從兩個列1,列2 FROM表1使用光標讀值。然後我想傳遞這些值到另一個遊標或選擇到語句 所以我的PL/Sql腳本將使用這兩列的值從另一個表中獲取數據稱爲table2如何將光標值傳遞給變量?

這可能嗎?什麼是最好和最快的方式來做這樣的事情?

謝謝:)

+1

refcursors對於這一點,但我總是猜測,子查詢可以完成相同..也可以考慮使用嵌套表(pl sql table)。您可以將嵌套表格轉換爲實際表格並用於查詢。 –

回答

0

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