在 PLSQL 中通过循环重建索引

Rebuild index through loop in PLSQL

FOR r IN (select 'DRR_DEV.' ||object_name as obj from dba_objects where object_type = 'INDEX' 
and owner ='DRR_DEV')
  LOOP
        l_sql := 'ALTER INDEX '||r.obj||' REBUILD'||'';
        execute immediate l_sql;
  END LOOP; 

在 FOR..IN 循环之上,循环特定模式的所有索引并重建。我在循环的开始和 ALTER 语句的行中得到了一些错误。

PL/SQL: SQL Statement ignored
PL/SQL: ORA-00942: table or view does not exist
PL/SQL: Statement ignored
PLS-00364: loop index variable 'R' use is invalid

我可以手动 运行 select 语句但不能通过 PLSQL 块,可能会出什么问题?

您似乎没有权限访问 DBA_OBJECTS。以 SYS 和 运行 这样的代码连接,或者 g运行t 需要其他用户的权限,或者 - 甚至更好 - 以 DDR_DEV.

连接

Ah, outside of PL/SQL it works - sorry, didn't notice that earlier. The fact is: privileges acquired via roles won't work in PL/SQL. So, if that's the case, grant SELECT ON DBA_OBJECTS directly to user that runs your PL/SQL code.

我删除了限制 OWNER 的条件,因为 USER_OBJECTS 中没有这样的列。

这是我的 SCOTT 用户 运行 的示例:

SQL> CREATE TABLE test (id NUMBER);

Table created.

SQL> CREATE INDEX i1
  2     ON test (id);

Index created.

SQL> DECLARE
  2     l_sql   VARCHAR2 (100);
  3  BEGIN
  4     FOR r IN (SELECT object_name AS obj
  5                 FROM user_objects
  6                WHERE object_type = 'INDEX'             -- AND owner = 'DRR_DEV'
  7                                           )
  8     LOOP
  9        l_sql := 'ALTER INDEX ' || r.obj || ' REBUILD' || '';
 10        DBMS_OUTPUT.put_line (l_sql);
 11
 12        EXECUTE IMMEDIATE l_sql;
 13     END LOOP;
 14  END;
 15  /
ALTER INDEX I1 REBUILD

PL/SQL procedure successfully completed.

SQL>