0

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

1

1 Answer 1

2

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;
/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.