How to create and use temporary table in oracle stored procedure?

前端 未结 5 774
挽巷
挽巷 2020-11-30 06:01

I want to create temporary table in stored procedure and access it in the same but I got error that ORA-00942:Table or view does not exists. Following is the pr

相关标签:
5条回答
  • 2020-11-30 06:31
    Create or replace procedure myprocedure
    is 
       stmt varchar2(1000);
       stmt2 varchar2(1000);
    begin
        stmt := 'create global temporary table temp(id number(10))';
        execute immediate stmt;
        stmt2 := 'insert into temp(id) values (10)';
        execute immediate stmt2;
    end;
    
    0 讨论(0)
  • 2020-11-30 06:36

    Just create it first (once, outside of your procedure), and then use it in your procedure. You don't want to (try to) create it on every call of the procedure.

    create global temporary table tmp(x clob)
    on commit delete rows;
    
    create or replace procedure...
    -- use tmp here
    end;
    
    0 讨论(0)
  • 2020-11-30 06:42

    I have edited this answer as it was wrong. I am a recent MSSQL convert and because of the way oracle implements global temp tables, if you really DO need to use temp tables, creating them once and leaving them there is the way to go. Unless you use dynamic sql in your procs exclusively (have fun debugging), you will not be able to successfully compile your package unless the tables referenced already exist. Oracle validates any objects referenced in methods that you attempt to compile, which is why you got the 942 error. I love the way Oracle manages scope with these global temp tables. That, alone, sold me on the idea.

    0 讨论(0)
  • 2020-11-30 06:49

    Use this

    Create of replace procedure myprocedure
    is 
       stmt varchar2(1000);
       stmt2 varchar2(1000);
    begin
        stmt := 'create global temporary table temp(id number(10))';
        execute immediate stmt;
        stmt2 := 'insert into temp(id) values (10)';
        execute immediate stmt2;
    end;
    
    0 讨论(0)
  • 2020-11-30 06:55
    CREATE OR REPLACE PROCEDURE myproc IS
    BEGIN
    
        CREATE GLOBAL TEMPORARY TABLE temp (id NUMBER(10)) ON COMMIT DELETE ROWS AS
            SELECT 10 FROM dual;
    
    END;
    /
    
    0 讨论(0)
提交回复
热议问题