1

I would like to run the FOR LOOP in Oracle based on a parameter that is dynamically populated. Please see, how the code could look like:

declare
    idx number := (select max(field_name) from table_name); 

begin    
    for i in 1..idx loop
        dbms_output.put_line (i);
    end loop;
end;

So basically if the select max(field_name) from table_name returns for example 10, the loop should be run 10 times (for i in 1..10 loop).

1 Answer 1

2

Assuming that field_name is an integer, you only need to fetch the max value in the right way:

declare
    idx number; 
begin    
    select max(field_name)
    into idx
    from table_name;
    if idx is not null then  -- to handle the case where the table is empty
        for i in 1..idx loop
            dbms_output.put_line (i);
        end loop;
    end if;
end;

or, without the IF:

declare
    idx number; 
begin    
    select nvl(max(field_name), 0)
    into idx
    from table_name;
    for i in 1..idx loop
        dbms_output.put_line (i);
    end loop;
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.