[英]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.