简体   繁体   中英

Dynamic loop in PL/SQL

I am currently looping through values in PL/SQL with the following:

for c in (select * from example_table where name is not null) loop  
  -- logic  
end loop; 

I would like to replace the SQL statement with a dynamic one, for example:

l_sql := 'select * from example_table where || l_col || is not null';  
for c in (l_sql) loop  
  -- logic  
end loop;  

Is this possible?

Best regards

That's not possible with an implicit cursor loop ( select inside for loop ). You may use the conventional OPEN .. FETCH .. LOOP through a REFCURSOR with a record variable of tablename%ROWTYPE

DECLARE
t_rec  example_table%ROWTYPE;
l_sql  VARCHAR2(1000);
v_cur SYS_REFCURSOR;
l_col varchar2(32) := 'MY_COLUMN';
BEGIN
  l_sql := 'select * from example_table where '|| l_col || ' is not null';  

OPEN v_cur FOR l_sql;
   LOOP
      FETCH v_cur INTO t_rec; --fetch a row 
         EXIT WHEN v_cur%NOTFOUND;

    -- your logic using t_rec columns.
   END LOOP;
CLOSE v_cur;

END;
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM