If I create a procedure:
CREATE OR REPLACE PROCEDURE SchameB.PRC_GATHER_STATS IS
BEGIN
SYS.DBMS_STATS.GATHER_TABLE_STATS( 'SchName', 'TableName', CASCADE => TRUE);
END;
and execute it ;
EXEC SchameB.PRC_GATHER_STATS;
this gives me error ORA-20000: Unable to analyze TABLE "SchameA"."TableName", insufficient privileges or does not exist. But this works:
EXEC SYS.DBMS_STATS.GATHER_TABLE_STATS( 'SchameA', 'TableName', CASCADE => TRUE);
The user who EXECs the procedure and the table are in different schemas.
Why am I getting an error when doing this through a procedure?
To gather statistics on an object in another schema you need the
ANALYZE ANYsystem privilege. I appears that the user that runs your procedure has that privilege, but granted through a role. As the documentation says:You can either
GRANT ANALYZE ANYdirectly to your user, or create the procedure with invoker’s rights, as:When you
EXECtheDBMS_STATSprocedure directly, it’s running as an anonymous block, and those always run with invoker’s rights – honouring roles.