Search code examples
oraclestored-proceduresplsqldatabase-metadataexecute-immediate

Procedure which gives grants, Invalid table name error


I'm trying to create a procedure which gives grants to specific schema objects. Procedure seems to compile ok, but it gives an error when execution.

Something is wrong in this simple procedure but I cannot find the reason for this.

Procedure:

create or replace procedure ch.grants_to_schema_objects(
          i_target_schema varchar2, 
          i_target_user varchar2) as
begin
 for mt in (SELECT 'GRANT SELECT ON ' || chr(39) 
              || i_target_schema || chr(39) 
              || '.' || TABLE_NAME || ' TO ' || chr(39) 
              || i_target_user || chr(39)
              || ' WITH GRANT OPTION' as grnt 
          FROM ALL_TABLES 
          WHERE OWNER = i_target_schema) loop
  dbms_output.put_line(mt.grnt);
  execute immediate mt.grnt;
end loop;
end;

call:

 execute ch.grants_to_schema_objects('SR', 'CH');

Error:

ORA-06512: "CH.GRANTS_TO_SCHEMA_OBJECTS", line 5
ORA-06512: line 1
00903. 00000 -  "invalid table name"
*Cause:    
*Action:

Solution

  • The CHR(39) is breaking it. Replace it whit CHR(34): it is " you need to separate your username, not '.