Using temporary tables in stored procedures

Suppose that I have created a temporary table in a stored procedure using an "EXECUTE IMMEDIATE" statement. When I compile the procedure, that table is not created yet, so the compiler says that the table does not exist.
What is the way of using temporary tables in stored procedures?

It's a good practice to avoid using DDL statements being executed from stored procedures. "Truncate Table" via dynamic SQL from stored procedure is a different story and is useful in DSS environments.
But if you insist on "creating" tables using Dynamic SQL from Stored Procedures then you must also embed your DML statements in Dynamic SQL to avoid compilation errors.
Example:
Create or Replace Procedure Proc_TestDynamicSQL is
Begin
Execute Immediate 'Create table myTable as select * from user_tables' ;
Execute Immediate 'Update myTable set table_name = ''Test'' ' ; --two single quotes before and after the string "Test"
End;
In this case, Oracle wouldn't care about the table references during compilation.

Similar Messages

  • Temporary Tables in Stored Procedure

    Hi,
    I am writing a stored procedure that will get data from different sources and generates a spreadsheet finally. Initial select gets the basic data and following selects merges data.
    For this I have created a table in the database, I am populating data into that table using same procedure and finally selecting data from that table to generate spreadsheet.
    Now I am planning to use TEMPORARY table instead of creating table in database. Can anyone tell me where I can view samples for temp tables?
    Which one is the better option in performance wise?
    or
    can I handle the whole scenario with cursor? any examples?

    Hi,
    Why can't you use a regular table?
    Look up [Global Temporary|http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_7002.htm#sthref7247] in the diocumentation, including the SQL*Language manual, for an alternative.
    "Temporary" applies only to the data. A Global Temporary Table is created once, and stays until you DROP it, the same as any other table.
    The data in the table is temporary. If you create the table saying "ON COMMIT PRESERVE ROWS" (which sounds appropriate, based on your description) the the data will automatically be deleted when you end the database session.
    All data in Global Temporary Tables is session-specific. If two (or more) people are using the same table at the same time, each will only see the data they inserted themselves; they will never see rows inserted by the other session.
    Almost anything you can do with a regular table you can do with a Global Temporary Table. In particular, DML (such as MERGE) and cursors work exactly as they do on other tables.

  • Problem with temporary table in stored procedure

    Hi,
    I have to execute a stored procedure in java , where the stored procedure has refcursor as out parameter and within the procedure the refcursor out parameter is populated from a temporary table
    when iam trying to get the resultset in my program iam getting the oracle error: ora-08103 object is no longer in use.
    I think this is becos the temporary table object is not available to my program
    can any one please help me

    I don't understand this part.
    Your procedure has "argSchemaName" as input parameter. Why do you have hardcoded owner name here in the cursor?
    >>
    CURSOR csrEligTables IS
    SELECT
    object_name
    FROM
    all_objects
    WHERE
    Owner = 'HI0XXX001'
    AND
    >>
    The anonymous block that you are running also has same owner name.

  • Using truncate table in stored procedure

    Hello
    I am trying to truncate and repopulate a table in a procedure. I have found that this appears to be impossible. Surely there is some way around this!!
    Can anyone help me overcome this problem?
    Dean
    null

    Use the DBMS_SQL package or (in 8i) execute immediate.

  • Sys Tables In Stored Procedure

    How can I use Sys Table in Stored Procedure.
    I want to use DBA_TAB_COLOUMNS, in stored procedure.
    When I used this table in stored procedure I got an error
    ORA - 00942 Table or View Does not exists.
    Thanks,
    Ahamed

    From http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_packages.htm#i1006224
    >
    Note:
    To create without errors (to compile the procedure or package successfully) requires the following additional privileges:
    The owner of the procedure or package must be explicitly granted the necessary object privileges for all objects referenced within the body of the code.
    The owner cannot obtain required privileges through roles.
    >
    You need to run
    grant select on dba_tab_columns to <owner of procedure>;

  • Getting different result while running Dashboard SP Using Temporary table?

    Hi Experts
    I am getting different result when I run my dashboard procedure I am using temporary table with "ON COMMIT PRESERVE ROWS", below is the information
    I am running my attendance dashboard procedure which will display the employee attendance status based IN and OUT punches the status like AA-full day absent, GG-Full day Present, AG-First half absent,GA-Second half absent. Now when I run the first time my procedure for first time I am getting status AA even though IN and OUT timings are correct and if run it again then it is displaying the status for same employee as GG
    I didn't understand the problem where it is effecting the status

    ChakravarthyDBA wrote:
    It is procedure which will display the employee status, back end I am storing the procedure result in Temporary table with "ON COMMIT PRESERVE ROWS", when I run the procedure first time it is showing wrong information when I run it again second time then it is showing correct information. I don't know why the status is changing.
    first time employee status is AA --Full day absent and Second time is GG--Full day present (in both cases IN and OUT timings are correct only)
    is it effecting due to temporary table?
    So, you have a GTT and you're doing "something" with it and that "something" isn't what you expect.
    I've about summed up what you've posted and given us to work with. If you have specific examples please do share. Without them we're going to be of very little use to you.
    If you aren't getting the results you expect, it stands to reason that
    1) you don't understand the outputs you are supposed to be getting
    2) you have a bug in the code developed
    Please stop and think about this, pretend you are the one trying to help out. You've been given little to no information about a system you've never seen before. You need to explain your situation as you would if you brought someone in to your shop to show them this problem you are having ... the rules don't change just because it's not face-face interaction.
    Cheers,

  • Using Copy statement in Stored procedure

    The following statement works in sqlplus session:
    copy from comment/password@servername append amcomment_temp using
    select * from amcomment
    where commentid in(1,2,3,4)
    I want to use this in a stored procedure. There is a long datatype in this table. The
    procedure will not compile. Have tried execute immediate and compiler rejects this statement also.

    'COPY' is a SQL*Plus command, not PL/SQL. This is why the PL/SQL compiler throws it out.

  • How to use Temporary Table in PL-SQL

    In MySQL there is no Temporary table concept.
    So for intermediate calculation I have created a table as below
    create table SequenceTempTable
    SessionId VARCHAR(50),
    Sequence VARCHAR(500),
    CreatedDate DATE
    ) ENGINE=MEMORY;
    Whenever I invoke a SP, I load the data into SequenceTempTable using Session Id as below
    CREATE PROCEDURE `GetSequence`(
    IN Start_Date VARCHAR(25),
    IN End_Date VARCHAR(25)
    BEGIN
    SELECT UUID() INTO v_SessionId;
    INSERT INTO SequenceTempTable values (v_SessionId,'1,2,5,3',now());
    required code
    DELETE FROM SequenceTempTable WHERE SessionId = v_SessionId;
    COMMIT;
    END;
    i.e. I have created a table as temporary table (created once),
    and load the data using Session Id and once session specific intermediate computation done,
    I deleted the session specific data.
    Could you give me examples of How to use Temporary table in PL-SQL code with respect to my above example.
    Because I have gone through creating Temporary table but I stuck with use in PL-SQL. I mean to say Is there any need of creating table in advance before invoking SP.
    And one more thing as in MySQL temp table I created which is using MEMORY engine i.e. this table will always be in MEMORY so there is no need of writing data on disk.
    Regards
    Sanjeev

    Hi Sanjeev
    Read about GTT here
    http://www.oracle-base.com/articles/8i/TemporaryTables.php
    GTT always contains just session specific data. \
    In case you want to use the GTT in the same session again you can use option
    ON COMMIT PRESERVE ROWS;
    Or if it is used just once in the session use can use
    ON COMMIT DELETE ROWS;
    Do remember that for GTT the data of one session can not be accessed in other session.
    Also you can go away with Delete from GTT if not used again in same session.
    Regards
    Arun

  • Drop and recreate table in stored procedure

    Hi all
    When creating tables using Transact-SQL scripts, I have always preferred to drop the table if it exists and then create it explicitly using CREATE TABLE.  For two reasons:
    1) It does not matter if it is the first time the SP is run ie. if I create the table manually in the first instance and just use TRUNCATE TABLE it could fail if the table is deleted
    2) I have control over the data types of the table fields
    Just recently though I discovered the error that can occur when dropping and creating a table in the same batch (see link below)
    Microsoft Website
    This causes me a problem when dropping and creating tables in stored procedures, as I understand that a stored procedure is in itself a single batch?
    Can I avoid this error in a stored procedure whilst continuing to drop and create tables?  Or should I be taking a different approach?
    Coding best practice advice would be greatly appreciated.
    Thank you

    Thanks Ronen
    Please see my second post immediately before your reply.
    Given that I need to store the data output in a physical table for use in QlikView, would you suggest truncating the table each time the SP runs?  And then having a script that handles both dropping and creating the physical table, and also creating
    the SP?
    >> QlikView
    QlikView is an Israeli company, right?
    In any case I am not familiar with QlikView's application, therefore I can only give you general information, based on assumptions regarding the application, and facts regarding the SQL Server.
    >> for use in QlikView
    I assume that external application use specific database structure (table
    structure) and it is change only in rare situations (for example CMS interface might change the tables if and when a module s update/install). In this case there is no need to drop the table and recreate it and TRUNCATE is the solution.
    >> would you suggest truncating the table each time the SP runs
    I am sorry but i cant recommend on TRUNCATE a table each time you execute SP, without know the exact reason for this logic. It sound to me, at this point of time (with the information that we have), that this
    is very bad logic (application architecture). As I wrote above, basing your application on TRUNCATING the table each time mean that you have problems with multi users. Thins about 2 people that try to execute the same SP at almost the same time. Think about
    locking in the SQL Server and bad data (one truncate while the other already inserted the new data and get no rows, if there is no locking).
    But TRUNCATE is much better in this case probably then DROP and DELETE, since it is faster, and locking will be shorter (hopefully the application use the correct locking). There are other reasons why TRUNCATE is better, and other people already mentioned
    most of them, but time in this scenario might be critical.
    >> having a script that handles both dropping and creating the physical table, and also creating the SP?
    I do not undestand what is this second step. we said that you truncate the table, so why do you need to
    dropping and creating the physical table and who
    creating the SP?
    Are you meaning that the application create the tables and SP?
    There are lot of application that during installation create the database structure. is this what you mean?
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • Using VIEW inside a stored procedure

    Hi,
    So I have a View designed in one file that validates someone who is authorized.
    Then I have a stored procedure to display authorized stationeries created before a given date. Its takes a parameter @CreatedOn.
    How can I use VIEW in my stored procedure so I can display all the authorized which are set 1 before a given date?
    My VIEW:
    ALTER VIEW vw_AuthorizedStationeries AS
    SELECT Authorized
    FROM dbo.Stationeries
    WHERE Authorized = 1
    And my stored procedure:
    CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)ASBEGINSELECTFROMENDGO
    Thanks!

    Try something like below, You need to replace CreatedDate column with appropriate date column in your table.
    1. Alter the view to get the required date:
    ALTER VIEW vw_AuthorizedStationeries AS
    SELECT Authorized, CreatedDate
    FROM dbo.Stationeries
    WHERE Authorized = 1
    2. Alter SP:
    CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)
    AS
    BEGIN
    SELECT Authorized
    FROM vw_AuthorizedStationeries
    WHERE CreatedDate <= @CreatedOn
    END
    GO
    OR
    You can pull required information directly from your table:
    CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)
    AS
    BEGIN
    SELECT Authorized
    FROM dbo.Stationeries
    WHERE CreatedDate <= @CreatedOn and Authorized = 1
    END
    GO
    If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

  • Use database inside a stored procedure

    Hi guys, a stupid question: I'm working with several database and sometimes I'm afraid to run an alter or a create something in the wrong database, bear in mind that several database have the same tables. Sometime happens to run a query oin the db A
    instead in the db B. So, the question: If I create a procedure like this,
    create procedure creatingPillar as
    use USA
    begin
    IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
    OBJECT_ID(N'pillarretail') AND type in (N'U'))
    DROP TABLE PillarRetail
    create table PillarRetail (anid int , ancore varchar(20), period dec(18,6), settlem datetime2,
    settlementper int, asf dec(18,6),astlf dec (18,6), tot dec (18,6) )
    insert into PillarRetail select anid, ancore, Period, settlem, settlementper,
    asf, astlf, tot from createsemipillar2011
    insert into PillarRetail select select anid, ancore, Period, settlem, settlementper,
    asf, astlf, tot createsemipillar
    end
    but I'm wondering if is useless to put the use USA in the stored procedure by the moment that I'm creating the procedure in USA. I mean, having the SP in the USA db even if I run the procedure from another db it should run in USA. Just a stupid question
    I know but I got this doubt...
    Thanks 

    You may try as below:
    create proc as below: (This will create the proc in USA database.
    use USA
    Go
    create procedure dbo.creatingPillar as
    begin
    IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
    OBJECT_ID(N'pillarretail') AND type in (N'U'))
    DROP TABLE PillarRetail
    create table PillarRetail (anid int , ancore varchar(20), period dec(18,6), settlem datetime2,
    settlementper int, asf dec(18,6),astlf dec (18,6), tot dec (18,6) )
    insert into PillarRetail select anid, ancore, Period, settlem, settlementper,
    asf, astlf, tot from createsemipillar2011
    insert into PillarRetail select select anid, ancore, Period, settlem, settlementper,
    asf, astlf, tot createsemipillar
    end
    Then you can call as below:
    Exec USA.dbo.creatingPillar

  • How to use order by in stored procedure base block?

    How to use order by in stored procedure base block? I need to change order by dynamically

    Use SET_BLOCK_PROPERTY('BLOCK_NAME',ORDER_BY,'COLUMN_NAME1, COLUMN_NAME2');

  • Can rs.last() be used after calling the stored procedure?

    Can rs.last() be used after calling the stored procedure? If yes what should be the CURSOR types?

    Can rs.last() be used after calling the stored
    procedure? If yes what should be the CURSOR types?That would depend on the driver/database.
    And as I said in your other post it is far more efficient to count records by just returning a count rather than a complete collection regardless of how you get to the end.

  • Using Temporary Table in SSIS

    I have a dataflow task which puts the result in a temporary table. I want to put the table result in a flat file but is not able to do that. Can anyone help?
    Here is the sql code
    use adventureworks2008r2
    declare @totalcount as float
    declare @addcount as float
    declare @citycount as float
    declare @addperct as float
    declare @cityperct as float
    declare @temp table (name varchar (40), percentage float)
    set @totalcount = (select count(*)from person.Address)
    set @addcount = (select COUNT (*)from person.Address where AddressLine2 = null)
    set @citycount = (select COUNT (*) from person.Address where City is not null )
    set @addperct = 100*(@addcount/@totalcount)
    set @cityperct = 100*(@citycount/@totalcount)
    insert into @temp
    select 'Addressline2',ROUND (@addperct,2)
    insert into @temp
    select 'City',ROUND (@CITYPERCT,2)
    SELECT * FROM @temp

    What you're using is table variable and not temporary table. It will be out of scope outside batch so you cant use it anywhere after code.
    I think if you want to use it in further tasks you should use temporary tables (# tables) after setting RetainSameConnection property to true.
    See
    http://consultingblogs.emc.com/jamiethomson/archive/2006/11/19/SSIS_3A00_-Using-temporary-tables.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Using Temporary table as a target

    when i used real target table the integration works fine but when i used temporary table i got "com.sunopsis.tools.core.exception.SnpsSimpleMessageException: CKM not selected."
    I don't know why inspite of being importing the CKM
    do any one has any idea about this?

    Hi
    I have the same problem, and uncheck the option of FLOW CONTROL = NO and still remains error "com.sunopsis.tools.core.exception.SnpsSimpleMessageException: CKM not selected" .. Do you have any idea because I still ticking wrong?
    Edited by: user2080320 on 06-oct-2008 11:44
    Edited by: user2080320 on 06-oct-2008 11:45

Maybe you are looking for