1

So I have a block of PLSQL code that will drop all indexes as shown in the following block of code:

DECLARE
DRP_STMNT   VARCHAR2(100) := ''; 
BEGIN
    FOR I IN (SELECT INDEX_NAME FROM USER_INDEXES) LOOP
        DRP_STMNT := 'DROP INDEX ' || I.INDEX_NAME;
        EXECUTE IMMEDIATE DRP_STMNT;
    END LOOP;
END;
/

That will do the job but should I use a cursor instead of embedding my SELECT statement within the FOR LOOP?

Does the FOR LOOP look at the entire table or does it process one row at a time?

What do you guys suggest using and why?

4
  • 1
    There's no need to use an explicit cursor here. Commented Aug 22, 2018 at 20:30
  • @APC would that be the same case if I want to create it as a stored procedure? Commented Aug 22, 2018 at 20:39
  • Of course. Why wouldn't it? Commented Aug 22, 2018 at 21:00
  • Every select is a (implicit) cursor. Commented Aug 23, 2018 at 5:43

1 Answer 1

3

The result will be just the same.

Though, you'll consume some more energy as you'd have to type more characters as you have to declare a cursor and cursor variable, open a cursor, start the loop, fetch from it, take care about exiting the loop, close a cursor.

When you use a cursor FOR loop (as you did), there's much less typing as Oracle does lots of that for you. For free.

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

5 Comments

But will what I have right now perform the same way as if I had a cursor (which is basically pointing at each row at a time)?
You'd be doing it one-by-one either way, no difference.
@Littlefoot that's not strictly true; Oracle can and will turn cursor for loops into fetch ... bulk collect limit 100 style loops behind the scenes, assuming the plsql_optimize_level is >=2. For the OP: it doesn't matter whether the cursor is explicitly (declare cursor some_curosr is ...; begin for rec in some_cursor loop ...) or implicitly for rec in (select ....) loop, the behaviour of the loop is the same.
Ah! That's for advanced users, @Boneist. Didn't know that (obviously, I'm not that advanced person). Thank you!
@Littlefoot every day is a learning day *{:-) And now you are an advanced user, under your definition!

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.