簡體   English   中英

如何在oracle pl / sql中將表名用作嵌套for循環中的變量?

[英]How can I use table name as a variable in nested for loops in oracle pl/sql?

我有這樣的查詢:

 v_sql:= 'select count(1) from '||v_tbl||' where col1 = ' || month_var || ' and ds =''T''';
 execute immediate v_sql into v_row_cnt;

   for j in 1..v_row_cnt
    loop
      for i in (select b.* from
               (select a.*, rownum as rn
                from (select * from MY_TABLE where col1 = month_var and DS = 'T') a
                 ) b
               where rn=j)
      loop

          do_something;
      end loop;
     end loop;

現在,我的問題是,我不能在這里硬編碼MY_TABLE。 我需要使用變量。 我目前正在這樣做,因為我需要逐行處理數據。

任何想法如何做到這一點?

謝謝。 羅恩

您將使用動態SQL來構建游標。

這里的邏輯效率很低:首先計算給定表中的行數,然后為每一行執行一次相同的查詢( Schlemiel the Painter算法的另一個例子)。

您不需要這樣做,只需循環遍歷游標 ,這將只執行一次查詢。 例如:

SQL> DECLARE
  2     l_cursor SYS_REFCURSOR;
  3     l_table VARCHAR2(32) := 'ALL_OBJECTS';
  4     l_name VARCHAR2(32);
  5  BEGIN
  6     OPEN l_cursor FOR 'SELECT object_name
  7                          FROM ' || l_table
  8                    || ' WHERE rownum <= 5 ';
  9     LOOP
 10        FETCH l_cursor INTO l_name;
 11        EXIT WHEN l_cursor%NOTFOUND;
 12        -- do_something
 13        dbms_output.put_line(l_name);
 14     END LOOP;
 15     CLOSE l_cursor;
 16  END;
 17  /

C_OBJ#
I_OBJ#
TAB$
CLU$
C_TS#

您不需要事先計算行數,如果光標為空,則立即退出循環。

暫無
暫無

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

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