Skip to Main Content
  • Questions
  • Strange behaviour with excecute immediate.

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Ingimundur.

Asked: November 12, 2018 - 4:13 pm UTC

Last updated: November 12, 2018 - 5:37 pm UTC

Version: Oracle 11.2.0.4.0

Viewed 1000+ times

You Asked

Hi,

Had problems with SQLLive, (500 response), therefore the examples are her.

I have a strange behaviour with execute immediate, where it behaves differently from within a PL/SQL procedure than it does when running it standalone.

Here is the example:
I create a simple table
CREATE TABLE TEST01 
(
  ID NUMBER 
, TEXT VARCHAR2(100 CHAR) 
);


Then I create a very simple procedure that will create a table based on the original table
CREATE OR REPLACE PROCEDURE test02 AS
    
BEGIN
    EXECUTE IMMEDIATE 'create table ABCD as select * from TEST01' ;
    COMMIT ;
   
END test02;


When I run this:
begin
    test02();
end;


I receive the following error:
ORA-01031: insufficient privileges
ORA-06512: at "INGIMUNDUR.TEST02", line 4
ORA-06512: at line 2
01031. 00000 - "insufficient privileges"

But if I run:
BEGIN
    EXECUTE IMMEDIATE 'create table ABCD as select * from TEST01' ;
    COMMIT ;
   
END;


everything runs fine, with no errors.

Why is this discrepancy?

Regards,
Ingimundur K. Gudmundsson.

p.s. I also tested this on an Oracle XE 11g, and the behaviour is the same.

and Chris said...

That's because you need to grant "create table" to your user. Not inherit it via a role:

CREATE TABLE TEST01 (
  ID NUMBER 
, TEXT VARCHAR2(100 CHAR) 
);

CREATE OR REPLACE PROCEDURE test02 AS   
BEGIN
    EXECUTE IMMEDIATE 'create table ABCD as select * from TEST01' ;
    COMMIT ;
   
END test02;
/

exec test02();

ORA-01031: insufficient privileges

grant create table to chris;

exec test02();

desc ABCD;

Name   Null?   Type                 
ID             NUMBER               
TEXT           VARCHAR2(100 CHAR)   


You don't need this when running anonymous blocks. Only compiled PL/SQL.

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Thanks!!

Ingimundur Gudmundsson, November 13, 2018 - 2:01 pm UTC

Thanks Chris for the very quick reply. Oddly I did not know there was a difference in privileges like that, especially when one runs it as the same user. But it sounds logical though.

Regards
Ingimundur

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library