2013-01-08 103 views
3

我有2個表中的ID字段是通用的。如何從oracle存儲過程返回動態遊標

我正在獲取遊標中第一個表的所有記錄。 然後我想要做的是,根據遊標中的每個ID,我想從第二個表中獲取值,然後返回該值。

我該怎麼做... 請幫忙!!!

回答

2

作業?

這是基本的SQL。一般你會加入這兩張桌子。

begin 
    for r_row in (select b.* 
        from tab1 a 
         inner join tab2 b 
           on b.id = a.id) 
    loop 
    null; -- do whatever 
    end loop; 
end; 
/

,如果你有一個現存的遊標,不能改變它

例如當your_cursor只是返回一個ID列。

begin 
    open your_cursor; 
    loop 
    fetch your_cursor into v_id; 
    exit when your_cursor%notfound; 
    for r_row in (select * from tab2 b where b.id = v_id) 
    loop 
     null; -- do whatever here. 
    end loop; 
    end loop; 
end; 
/

編輯:每評論 爲:

一些樣本數據:

SQL> create table table1 (id number primary key, name varchar2(20)); 

Table created. 

SQL> create table table2 (id number, col1 varchar2(20), col2 varchar2(20)); 

Table created. 

SQL> insert into table1 values (1, 'test'); 

1 row created. 

SQL> insert into table1 values (2, 'foo'); 

1 row created. 

SQL> 
SQL> insert into table2 values (1, 'John', 'Smith'); 

1 row created. 

SQL> insert into table2 values (1, 'Peter', 'Jones'); 

1 row created. 

SQL> insert into table2 values (1, 'Jane', 'Doe'); 

1 row created. 

SQL> insert into table2 values (2, 'Nina', 'Austin'); 

1 row created. 

SQL> insert into table2 values (2, 'Naman', 'Goyal'); 

1 row created. 

SQL> commit; 

Commit complete. 

創建一個類型來保存,返回結構。注意數據類型需要匹配的表table1table2的數據類型(%類型將無法工作,所以要確保它們匹配)

SQL> create type my_obj as object (
    2 id number, 
    3 name varchar2(20), 
    4 col1 varchar2(20), 
    5 col2 varchar2(20) 
    6 ); 
    7/

Type created. 

SQL> create type my_tab as table of my_obj; 
    2/

Type created. 

現在創建功能(你可以把這個包中,如果在你真實的代碼,你有這種方式)。

SQL> create function function1 
    2 return my_tab pipelined 
    3 is 
    4 begin 
    5 for r_row in (select t1.id, t1.name, t2.col1, t2.col2 
    6     from table1 t1 
    7       inner join table2 t2 
    8         on t1.id = t2.id) 
    9 loop 
10  pipe row(my_obj(r_row.id, r_row.name, r_row.col1, r_row.col2)); 
11 end loop; 
12 end; 
13/

Function created. 

SQL> 
SQL> select * 
    2 from table(function1); 

     ID NAME     COL1     COL2 
---------- -------------------- -------------------- -------------------- 
     1 test     John     Smith 
     1 test     Peter    Jones 
     1 test     Jane     Doe 
     2 foo     Nina     Austin 
     2 foo     Naman    Goyal 

如果需要成的功能,例如table(function1('a', 'b'));等,你可以通過輸入..

+0

感謝您的答覆。 在以下代碼中 - –

+0

感謝您的回覆。 您提供的代碼爲r_row(select * from tab2 b where b.id = v_id) loop null; - 在這裏做任何事。 end loop; 在這段代碼中,我將從tab2中獲取值,但是我想保留tab2的這些值爲少數ID,並從存儲過程返回所有這些值。我如何做到這一點.. –

+0

@NamanGoyal你將如何使用它們?我們可以很容易地將它們作爲數組返回。會有幫助嗎?或者你想輸出作爲結果集(例如,你想做'從your_func()'或'return_array = your_func()'樣式選擇ID) – DazzaL

相關問題