0

I have a procedure body with a loop on the results of a query:

for src in (
    /* query A */
) loop
    /* 
     * loop body...
     */
end loop;

But I need to select between two or more different 'query A's depending on some condition. The queries are very different, but they all have the same resulting shape, namely one number column.

Is there a way to avoid having to repeat the loop code? Can I do something like this?

if /* some condition */ then
    query_A := /* ... */;
else
    query_A := /* ... */;
end if;

for src in (query_A) loop
    /* 
     * loop body...
     */
end loop;

I'm on Oracle 11g

1 Answer 1

1

Yes, you can use cursor like so:

DECLARE
    query_a     VARCHAR2(256);
    cur         SYS_REFCURSOR;
BEGIN
    IF /* some condition */ THEN
        query_a := 'SELECT column FROM table WHERE col1 = condition';
    ELSE
        query_a := 'SELECT column FROM another_table WHERE col2 = condition';
    END IF;

    OPEN cur FOR query_a;
    LOOP
        FETCH cur INTO var1, var2...varN; --> depending on how many rows you are retrieving
        EXIT WHEN cur%notfound;
        /* 
         * loop body...
         */
    END LOOP;
END;

Just note that this method will degrade your performance if your table starts to grow.

Sign up to request clarification or add additional context in comments.

4 Comments

why is query_a a varchar? do I need to put the text of the query in there?
Yes, you can build your query dynamically and then run it. I edited the answer, check it out.
Thanks. I'll wait a few days to see if other solutions crop up, otherwise I'll accept yours.
@Tobia Also take heed of the note.

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.