Search code examples
sqloracle-databaseplsqloracle12c

How to execute alter command within select statement in a loop in Oracle?


I am trying to Rebuild Indexes of a schema through a script but I am stucked at a point where I get the string ALTER INDEX OWNER.INDEX_NAME REBUILD NOLOGGING through select statement but I am not getting how to execute the alter command ,please guide :

I tried to assign str the value of select query used in 2nd for loop and then execute it but it gave error .

IS
STR VARCHAR2(5000);
BEGIN

    FOR T IN (
     SELECT USERNAME FROM DBA_USERS WHERE USERNAME ='REPORT'
      )
     LOOP
     
     FOR CUR IN 
     (
       SELECT ' ALTER INDEX '||OWNER||'.'||INDEX_NAME|| ' REBUILD NOLOGGING; ' FROM DBA_INDEXES 
         WHERE  OWNER=T.USERNAME AND TEMPORARY='N'
       )
        
        LOOP 
       --- EXECUTE IMMEDIATE STR ;
       INSERT INTO INDEX_REBUILD_HISTORY 
         SELECT DISTINCT  OWNER, TRUNC(LAST_DDL_TIME) from DBA_OBJECTS where OBJECT_TYPE = 'INDEX' 
         AND 
         OWNER=T.USERNAME ;
         COMMIT;
    
         
    END LOOP;
    END LOOP;
    
    END ; 

Solution

  • You use dynamic sql. And you don't need your outer loop. The filter on that is available in dba_indexes:

    create procedure bld_idx
    is
    vsql varchar2(500);
    
    for x in (select owner,
                     index_name
              from dba_indexes
              where owner = 'REPORT'
              and TEMPORARY='N'
              )
    loop
      vsql := ' ALTER INDEX '||x.OWNER||'.'||x.INDEX_NAME|| ' REBUILD NOLOGGING; ';
      dbms_output.put_line(vsql);  --  debugging only
      execute immediate vsql;
    end loop;
    end;
    

    Note 1: above is off the top of my head. There may be minor syntax issues, but if so you should be able to work them out.

    Not 2: Rebuilding indexes is not something that needs to be done in the normal course of things. Richard Foote is probably the foremost authority on the internals of oracle indexes, and he has this to say: https://richardfoote.wordpress.com/2007/12/11/index-internals-rebuilding-the-truth/