2012-03-09 57 views
6

我的問題不是太複雜,但我是PL/SQL的新手。通過光標PL/SQL循環

我需要根據特定條件從COMPANIES表中進行選擇。然後,我需要遍歷這些並將一些字段轉換爲不同的格式(我爲此創建了函數),最後使用此轉換後的版本加入到參考表中以獲取我需要的分數變量。所以基本上:

select id, total_empts, bank from COMPANIES where turnover > 100000 

遍歷這個選擇

insert into MY_TABLE (select score from REF where conversion_func(MY_CURSOR.total_emps) = REF.total_emps) 

這基本上是我所期待的事情。它稍微複雜一點,但我只是在尋找基礎知識,以及如何處理它才能讓我開始!

回答

11

這裏是基本的語法光標在PL/SQL循環:

BEGIN 

    FOR r_company IN (
     SELECT 
      ID, 
      total_emps, 
      bank 
     FROM 
      companies 
     WHERE 
      turnover > 100000 
    ) LOOP 

     INSERT INTO 
      my_table 
     SELECT 
      score 
     FROM 
      ref_table 
     WHERE 
      ref.total_emps = conversion_func(r_company.total_emps) 
     ; 

    END LOOP; 

END; 
/
3

你並不需要使用PL/SQL來做到這一點:

insert into my_table 
select score 
    from ref r 
    join companies c 
    on r.total_emps on conversion_func(c.total_emps) 
where c.turnover > 100000 

如果你必須這樣做在PL/SQL循環中,我會確保儘可能少做一些工作。但是,我會推薦bulk collect而不是循環。

begin 

    for xx in (select conversion_func(total_emps) as tot_emp 
       from companies 
       where turnover > 100000) loop 

     insert into my_table 
     select score 
     from ref 
     where total_emps = xx.tot_emp 
      ; 

    end loop; 

end; 
/

對於任一方法需要在ref.total_empscompanies.turnover

一個指數,優選一個