PL/SQL block to create temporary table + load via cursor for loop

Assume I have a table that contains a subset of data that I want to load into a temporary table within a cursor for-loop. Is it possible to have a single statement to create the table and load based on the results of the fetch?
I was thinking something like:
Declare CURSOR xyz is
CREATE TABLE temp_table as
select name, rank, serial number from
HR table where rank = 'CAPTAIN'
BEGIN
OPEN xyz
for name in xyz
LOOP
END LOOP
What I see wrong with this is that the table would be created multiple times which is why this syntax is not acceptable. I'd prefer not to have to define the temporary table then load in two sepearte SQL statements and am hoping a single statement can be used.
Thanks!

What is the goal here?
If you're just going to iterate over the rows that are returned in a cursor, a temporary table is unnecessary and only adds complexity. If you truly need a temporary table, you would declare it exactly once, at install time when you create all your other tables. You'd INSERT data into the temp table and the data would only be visible to the session that inserted it.
Justin

Similar Messages

  • Error creating temporary table

    I got this error when creating forms with ADDT. I checked MySQL reserved words and I'm sure that's not my problem :(. Any help with this?
    Many thanks
    Florencia
    Error:
    Error interno.
    Developer Details:
    tNG_fields.getFakeRecordset:
    SQL error: Error creating temporary table:
    Incorrect table name 'T'
    SQL:
    CREATE TEMPORARY TABLE KT_fakeRS_20071031 (fecha_ing TEXT, fecha_eg TEXT, seguro TEXT, compania TEXT, CC TEXT, T.T TEXT, chapa TEXT, pintura TEXT, mecanica TEXT, repuestos TEXT, TT TEXT, cerrado TEXT, patente TEXT, id_rep TEXT) (FIELDS_FAKE_RS_ERROR)
    tNG Execution Trace - VIEW

    Hi Florencia,
    a column name like "T.T" will always lead to such errors, because characters like a dot (.) are forbidden, so to speak -- MySQL table and column names may generally only contain alphanumeric characters (0-9, a-z, A-Z), and the only allowed separator would be an underscore (_)
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • Create Temporary Tables

    Hi, there.
    Can anybody tell me what's the syntax for the SQL statements to create temporary tables?
    I'm developing a shopping cart, and at the end of every purchase (checkout) I want to organize the items of the Session Bean Hash Table that contains them, and group them by category, brand, price and show the serial number of each item. I was thinking to do SQL-style operations like GROUP BY on the Hash Table itself, but I am having a hard time with it, so that's why I thought that filling a temporary database table with the Hash Table data could be the solution to the problem of grouping and ordering the items contained in the Shopping cart Bean.
    I saw the following code in this same forum:
    stmt = con.createStatement();
    stmt.executeUpdate("create table temp (slno integer, first_name varchar(32), middle_name varchar(1), last_name varchar(32))");
    But I don't understand how the temporary table has a fixed name, isn't that going to create conflict with another user that creates a temporary table with the same name but in a different session?
    I hope my approach makes sense. If so, what's the SQL syntax to create temporary-session-like tables so I can include it in my JDBC code?
    Thank you in advance for any information or alternative suggestion.

    But I don't understand how the temporary table has a
    fixed name, isn't that going to create conflict with
    another user that creates a temporary table with the
    same name but in a different session?Yes, it is. That's one reason why people try to avoid creating temporary tables, I suppose. There are other reasons.
    I hope my approach makes sense. If so, what's the SQL
    syntax to create temporary-session-like tables so I
    can include it in my JDBC code?You already know the syntax for creating a table. Your only problem is finding a unique name for the table, one that no other user will use. You could have a one-row one-column table with a number in it, which you read and increment, then use that number for your table name, for example. Unless your database happens to have this as a feature -- you would have to read its documentation to find that out.
    However as I implied before, you should try to avoid creating temporary tables. Creating a table is a time-consuming operation, and if your program ends abnormally without dropping the temporary table, your database slowly fills up with useless tables.

  • Create temporary Tables using SQL

    Hello,
    I'm wondering if SAP allows the creation of new Tables without SDK objects,
    I want to create temporary tables using SQL scripts an compile them when an specific addon is connected and erase them when the addon disconnects,
    Do you think this is allowed?.
    thanks,
    Gabriela

    You could always have a second DB to create your temp tables in.  This is the way I've done this, as well as created my own views and stored procedures in it.  No updating of the primary table necessary.  The way I named things was:
    Company_DB - Company Database
    Company_DB-Extern - My own stuff
    Then, in sap, you can just do [Company_DB-Extern]..Object to call it, or you do the same from withing your project.

  • How create temporary table from list of values

    Can you anybody advise me how can I create temporary table from list of values? I have list of values and need create temporary table for next use with command JOIN etc.
    Thank you for help

    NO, you can not create temporary table in oracle on the fly ( Like #Tabels in SQl Server or Sybase ) , you will have to use the GTT i.e Global Temporary Tables
    check the following link GTT :
    to flush the tables after commit
    CREATE GLOBAL TEMPORARY TABLE my_temp_table (
      column1  NUMBER,
      column2  NUMBER
    ) ON COMMIT DELETE ROWS;In contrast, the ON COMMIT PRESERVE ROWS clause indicates that rows should be preserved until the end of the session.
    so to keep rows in Table after commit
    CREATE GLOBAL TEMPORARY TABLE my_temp_table (
      column1  NUMBER,
      column2  NUMBER
    ) ON COMMIT PRESERVE ROWS;

  • Is there a way to create "temporary" tables in SAP database?

    Hello,
    Is there a way to create temporary tables in ABAP?
    Here is our scenario:
    1. Invoke a custom RFC that creates a temporary table and returns the name of the table.
    2. Invoke another custom RFC and pass this table name as parameter. This RFC internally does some INNER JOIN with the temporary table.
    3. Invoke the third RFC to delete the temporary table.
    Note that the name of the table cannot be static. We have many users using our application simultaneously and connecting to the SAP server.
    I would appreciate it if you could point me in the right direction.
    Thank you in advance for your help.
    Peter

    I just ran into a similar issue.  While only calling the select statement 2 times, each time had so many entries in the 'for all entries' list, that the compiler converted this into about 700 calls to the select.  Now since the select joined three real tables on the database, the trace shows this one select as being the slowest item in this application.
    I think that happened because 'for all entries' gets converted to an 'IN' clause, and then the total number of characters in any SQL statement has an upper limit.   So the compiler must make the select statement over and over until it covers all entries in the 'for all entries' list.  Is that correct?
    Since every database I ever saw has the concept of db temporary tables, I have used db temp tables many times for this sort of thing.
    The ABAP compiler could determine that more than one IN statement will be need, then use an alternate: write all the FOR ALL ENTRIES to a db temp table, then join on the db temp table, then drop db temp table.  Since the compiler does this sort of thing, no application code needs change to get the speed boost.

  • Create Temporary table

    Dear All
    Am using SAP B1 pl-40
    SQL Server 2005
    through Query manager if i create Temporary table it will make any
    problem?
    The following Example are am going to use
    create table ##baz
    CarIndex smallint,
    CarType varchar(20),
    cardcode varchar(20)
    insert into ##baz values('1','2','3')
    select * from ##baz
    drop table ##baz

    You'll not have any problems in Creating/ Inserting to your own created tables(without which you cannot develop an Add-on).
    You are not supposed to Insert or Delete into SAP tables using direct Insert/ Update/ Delete statements.
    Please Check this SAP Note: 896891     Support Scope for SAP Business One - DB Integrity
    [https://websmp130.sap-ag.de/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/smb_searchnotes/display.htm?note_langu=E&note_numm=896891]

  • Creating temporary tables with JSTL

    I need to create temporary tables in my DB (MySQL), and later call it in a query.
    I try this:
    <sql:update var="temp1" dataSource="${conn}">
    CREATE TEMPORARY TABLE temp1
    SELECT data1 FROM table1 WHERE condition = 1
    </sql:update>
    <sql:query var="query1" dataSource="${conn}">
    SELECT * FROM temp1
    </sql:query>

    I haven't done enough with MySQL recently to know.
    Break your problem up into two parts.
    First there's the query portion. Create a permanent table and make sure that your query works fine with taht.
    Next is the creation of the temporary table. Once you KNOW the query is working, then you can concentrate on that.
    I'll assume that you've already GRANTed table creation permission to the user that your JSP app uses to log into the database.
    Are there any messages written to the servlet/JSP engine log file that might help you figure out what's wrong? Do you have a JSP error page that's displayed if any exceptions are thrown? - MOD

  • Cannot create temporary table having identity column

    Hi experts,
    I saw the above error msg while running the following statement:
           create local temporary column table #tmp_table (c1 int GENERATED by default AS IDENTITY (start with 1 increment by 1), c2 int)
         Could not execute 'create local temporary column table #tmp_table(c1 int GENERATED by default AS IDENTITY (start with ...'
         SAP DBTech JDBC: [7]: feature not supported: cannot create temporary table having identity column: C1: line 1 col 48 (at pos 47)
    I understand we can support normal column table creation with identity column, but don't know why cannot support temporary column tables with identity column. Is there any configuration that can enable it for temporary column table? Or what can I do to support it indirectly, like writing a trigger to support it or something else?
    If not, then is there any future plan for this feature?
    Regards,
    Hubery

    Hi Hubery,
    I've heard this trail of arguments before...
    Customer has a solution... they want it on HANA... but they don't want to change the solution.
    Well, fair call, I'd say.
    The problem here is: there's a mix-up of solution and implementation here.
    It should be clear now, that changing DBMS systems (in any direction) will require some effort in changing the implementation. Every DBMS works a bit different than the others, given "standard" SQL or not.
    So I don't agree with the notion of "we cannot change the implementation".
    In fact, you will have to change the implementation anyhow.
    Rather than imitating the existing solution implementation on ASE, implement it on SAP HANA.
    Filling up tons of temporary tables is not a great idea in SAP HANA - you would rather try to create calculation views that present the data ad hoc in the desired way.
    That's my 2 cts on that.
    - Lars

  • Create temporary table as

    Hi every body!
    Can I use follow statement:
    "Create global temporary table AAA as select * from other table " to create temporary table ?
    Thank you very much.

    here it goes
    SQL> Select *
      2  From a1;
    N
    1
    3
    1
    SQL>
    SQL> create global temporary table temp_a3
      2  on commit preserve Rows
      3  As Select * From a1
      4  /
    Table created
    SQL> Select * From temp_a3;
    N
    1
    3
    1regards
    nic

  • Oracle SQL template to create re-usable DDL/DML Scripts for Oracle database

    Hi,
    I have a requirement to put together a Oracle SQL template to create re-usable DDL/DML Scripts for Oracle databases.
    Only the Oracle DBA will be running the scripts so permissions is not an issue.
    The workflow for any DDL is as follows:-
    1) New Table
    a. Check if the table exists from the system/admin views.
    b. If table exists then give message "Table Exists"
    c. If table does not exist then execute DDL code
    2) Add Column
    a. Check if Column exists for a given table from system/admin views
    b. If column exists in the specified table,
    b1. backup table.
    b2. alter table to make changes to the column
    b3. verify data or execute dml script convert from backup to the new change.
    c. If Column does not exist
    c1. backup table
    c2. alter table to add column
    c3. execute dml to populate column with default value.
    The DML scripts are for populating base tables with data required for business operations.
    3) Add new row
    a. check if row exists by comparing old values of each column with new values to be added for the new record.
    b. If exists, give message row exists
    c. If not exists, add new record.
    4) Update existing record (We have createtime columns in these tables so changes can be tracked)
    a. check if row exists using primary key.
    b. If exists,
    b1. deactivate the record using the "active" column of the table
    b2. Add new record with the changes required.
    c. If does not exist, add new record with the changes required.
    Could you please help with some ideas which can get this done accurately?
    I have tried several ways, but I am not able to put together something that fulfills all requirements.
    Thank you,

    First let me address your question. (This is the easy part.)
    1. The existence of tables can be found in DBA_TABLES. Query it and and then use conditional logic and execute immediate to process the DDL.
    2. The existence of table columns is found in DBA_TAB_COLUMNS. Query it and then conditionally execute your DDL. You can copy the "before picture" of the table using that same dba view, or even better, use DBMS_METADATA.
    As for your DML scripts, they should be restartable, reversible, and re-run-able. They should "fail gracefully" on error, be written in such a way that they can run twice in a row without creating duplicate changes.
    3. Adding appropriate constraints can prevent invalid duplicate rows. Also, you can usually add to the where clause so that the DML does only what it needs to do without even relying on the constraint (but the constraint is there as a safeguard). Look up the MERGE statement to learn how to do an UPSERT (update/insert), which will let you conditionally "deactivate" (update) or insert a record. Anything that you cannot do in SQL can be done with simple procedural code.
    Now, to the heart of the matter...
    You think I did not understand your requirements?
    Please be respectful of people's comments. Many of us are professionals with decades of experience working with databases and Oracle technology. We volunteer our valuable time and knowledge here for free. It is extremely common for someone to post what they feel is an easy SQL or PL/SQL question without stating the real goal--the business objective. Experienced people will spot that the "wrong question" has been asked, and then cut to the chase.
    We have some good questions for you. Not questions we need answers from, but questions you need to ask yourself and your team. You need to reexamine this post and deduce what those questions are. But I'll give you some hints: Why do you need to do what you are asking? And will this construct you are asking for even solve the root cause of your problems?
    Then ponder the following quotations about asking the right question:
    Good questions outrank easy answers.
    — Paul Samuelson
    The only interesting answers are those which destroy the questions.
    — Susan Sontag
    The scientific mind does not so much provide the right answers as ask the right questions.
    — Claude Levi-Strauss
    You can tell whether a man is clever by his answers. You can tell whether a man is wise by his questions.
    — Mahfouz Naguib
    One hears only those questions for which one is able to find answers.
    — Friedrich Nietzsche
    Be patient towards all that is unresolved in your heart and try to love the questions themselves.
    — Rainer Maria Rilke
    What people think of as the moment of discovery is really the discovery of the question.
    — Jonas Salk
    Judge a man by his questions rather than his answers.
    — Voltaire
    The ability to ask the right question is more than half the battle of finding the answer.
    — Thomas J. Watson

  • Cursor For Loop SQL/PL right application? Need help with PL Performance

    I will preface this post by saying that I am a novice Oracle PL user, so an overexplanation would not be an issue here.
    Goal: Run a hierarchial query for over 120k rows and insert output into Table 1. Currently I am using a Cursor For Loop that takes the first record and puts 2 columns in "Start" section and "connect by" section. The hierarchial query runs and then it inserts the output into another table. I do this 120k times( I know it's not very efficient). Now the hierarchial query doesn't take too long ( run by itself for many parts) but this loop process is taking over 9 hrs to run all 120k records. I am looking for a way to make this run faster. I've read about "Bulk collect" and "forall", but I am not understanding how they function to help me in my specific case.
    Is there anyway I can rewrite the PL/SQL Statement below with the Cursor For loop or with another methodology to accomplish the goal significantly quicker?
    Below is the code ( I am leaving some parts out for space)
    CREATE OR REPLACE PROCEDURE INV_BOM is
    CURSOR DISPATCH_CSR IS
    select materialid,plantid
    from INV_SAP_BOM_MAKE_UNIQUE;
    Begin
    For Row_value in Dispatch_CSR Loop
    begin
    insert into Table 1
    select column1
    ,column2
    ,column3
    ,column4
    from( select ..
    from table 3
    start with materialid = row_value.materialid
    and plantid = row_value.plantid
    connect by prior plantid = row.value_plantid
    exception...
    end loop
    exception..
    commit

    BluShadow:
    The table that the cursor is pulling from ( INV_SAP_BOM_MAKE_UNIQUE) has only 2 columns
    Materialid and Plantid
    Example
    Materialid Plantid
    100-C 1000
    100-B 1010
    X-2 2004
    I use the cursor to go down the list 1 by 1 and run a hierarchical query for each row. The only reason I do this is because I have 120,000 materialid,plantid combinations that I need to run and SQL has a limit of 1000 items in the "start with" if I'm semi-correct on that.
    Structure of Table it would be inserted into ( Table 1) after Hierarchical SQL Statement runs:
    Materialid Plantid User Create Column1 Col2
    100-C 1000 25 EA
    The Hierarchical query ran gives the 2 columns at the end.
    I am looking for a way to either just run a quicker SQL or a more efficient way of running all 120,000 materialid, plantid rows through the Hierarchial Query.
    Any Advice? I really appreciate it. Thank You.

  • Creating temporary table in pl/sql block problem

    hello
    i have a problem in creating and using temporary table in pl/sql block
    please verify below block
    begin
    execute immediate 'create global temporary table alitemp1 (co_t varchar2(10),color varchar2(10))';
    insert into alitemp1 (co_t,color) values ('001','red');
    execute immediate 'DROP TABLE alitemp1';
    end;
    when i execute that block i will receive this error
    insert into alitemp1 (co_t,color) values ('001','red');
    ERROR at line 3:
    ORA-06550: line 3, column 14:
    PL/SQL: ORA-00942: table or view does not exist
    ORA-06550: line 3, column 2:
    PL/SQL: SQL Statement ignored
    i think it because that alitemp1 table don't create
    but two below block run fine
    begin
    execute immediate 'create global temporary table alitemp1 (co_t varchar2(10),color varchar2(10))';
    execute immediate 'DROP TABLE alitemp1';
    end;
    begin
    execute immediate 'create global temporary table alitemp1 (co_t varchar2(10),color varchar2(10))';
    end;
    select table_name from user_tables where table_name='ALITEMP1';
    TABLE_NAME
    ALITEMP1
    it means that problem is when the below line exists in block
    insert into alitemp1 (co_t,color) values ('001','red');
    if may please guide me

    In addition to the comments by Justin and 3360, you cannot do what you want the way you are doing it.
    All objects referred to in a PL/SQL block must exist at the time the block is compiled. In your case, since it is an anonomous block, that is run time. Since you are dynamically creating the temporary table you need to refer to it dynamically as well. More like:
    BEGIN
    EXECUTE IMMEDIATE 'create global temporary table alitemp1 (co_t varchar2(10),
                                                               color varchar2(10))';
    EXECUTE IMMEDIATE 'insert into alitemp1 (co_t,color) values (:b1,:b2)' USING '001', 'red';
    EXECUTE IMMEDIATE 'DROP TABLE alitemp1';
    END;However, don't do that it is a really bad idea. Just create the temporary table, if you really need it, once and use it in your processing.
    In most cases, things that SQL Server needs temporary tables for can be done easily in Oracle with a single SQL statement,
    John

  • PL/SQL block to populate a table

    Hello Gurus,
    Need help to write a pl/sql block as per below:
    1. Write a PL/SQL block which will populate the RESULTS table as described below. Consider performance implications (specifically where would you commit the queries) as we are dealing with millions of records.
    The PL/SQL will:
    - insert into the RESULTS table each customer id, and the number of unique products purchased by that customer.
    - update the recently_purchased column of the customer table to 'Y' (yes if they have purchased a product in the last 12 months) or 'N' (if they have not purchased a product in the last 12 months).
    Listed below are the tables & definitions:
    table: CUSTOMER
    columns:
    customer_id NUMBER,
    customer_name VARCHAR2(100),
    recently_purchased VARCHAR2(1) -- 'Y' or 'N'
    table: CUST_PRODUCTS
    columns:
    product_id NUMBER,
    customer_id NUMBER,
    date_purchased DATE
    table: RESULTS
    columns: customer_id NUMBER, product_count NUMBER
    Thanks a lot..

    Hi Guys,
    I've tried this to my best but I feel like something's definately wrong with my update statement.
    Please help..
    --create customer table
    create table customer (
    customer_id number(6),
    customer_name varchar2(100),
    recently_purchased varchar2(1));
    -- describe to see if it is created as required
    desc customer
    --populate customer table with random values
    Begin
    For i in 1..20
    Loop
    Insert into customer(customer_id,customer_name,recently_purchased)
    values(i, dbms_random.string('U',5),'N');
    If mod(i, 100000) = 0 then
    Commit;
    End if;
    End loop;
    End;
    --create cust_products table
    create table cust_products
    (product_id number (6),
    customer_id number(6),
    date_purchased date);
    --describe to see if table is created as required
    desc cust_products
    --populate cust_products with custome_id 1 to 10 and dates
    Begin
    For i in 1..20
    Loop
    Insert into cust_products
    values(dbms_random.value(555,999),i,add_months('04-Nov-08',i));
    If mod(i, 100000) = 0 then
    Commit;
    End if;
    End loop;
    End;
    select * from cust_products
    --update customer table as required
    Begin
    For i in 1..10
    Loop
    update customer set recently_purchased = 'Y';
    commit;
    update customer C set recently_purchased = 'N' where exists (select date_purchased from cust_products P where C.customer_id = P.customer_id );
    commit;
    End loop;
    End;
    --Insert into results table
    select customer_id,count(product_id)
    from cust_products
    group by customer_id
    Edited by: user497841 on Feb 4, 2010 2:12 PM

  • Query hint to force SQL to use a temporary table in a CTE query?

    Hi,
    is it possible to tell SQL Server to create a temporary table by itself when I'm using a CTE in my query?
    I have a query starting with a CTE where I group by my record, then another recursive CTE use the first CTE and finally my select statement like:
    with cte as (select a,b,c,row_number() ...  from mytable group by a,b,c)
    , cte2(select .... from cte A where rownum =1
    union all select ... from cte B inner join cte2 C on ......
    select * from cte2
    this query is very very slow, but if I store the first CTE into a temporary table and then cte2 consume my temp table rather than the CTE, the query is very fast.
    creating the temp table took 10sec and the select took 20sec
    while the initial query didnt return anything  after 2minutes!!!
    so what can I try to do to have the query running in less than 30sec without creating the temp table first?
    is there a query hint which can be used to tell SQL Server to convert the CTE into a temp table?
    as I have a lot of query to manage, I want to simplify my model without relying in temporary tables every time I suffer this issue...
    thanks.

    What is your SQL Server version?
    There is no hint to materialize results of cte into a temp table, so the solution you tried is the best you can have.
    I think the idea of materializing CTE into a temp table was already proposed on Connect. Try searching for this and vote.
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

Maybe you are looking for

  • Problem in using 6670 with T-Mobile.. need urgent ...

    hiya there ive got a strange problem with my 6670 the problem is specifically with using T-Mobile uk when i put my T-Mobile sim in the phone i can make phone calls and recieve txts but it just only recieve phone calls from the same network i.e T-Mobi

  • Multiclip angles dissappear

    Help .. Could anyone tell me why my multiclip angles dissappear from the viewer as soon as I hit play. Only the active angle shows. They come back when I stop. Sometimes it all works fine, sometimes it doesn't .. and I don't seem to be doing anything

  • ITunes mixes up the track order of songs within an album??

    My iTunes mixes up the track order, and there is no way to specifically order it by track.  i have even gone and individually marked each song as ie(2 of 12) but it still lists them in a random order.  How can I make the songs fit in their original o

  • Consolidation Error Documentation (CSD)

    Hi all, I have recently ended upon a consolidation engine error (CSD-070, CSD-080). Searching in the forum I have see some threads talking about some documentation about these errors. Could anyone please send that documentation? About the CSD-070 (No

  • Problem With Song List In Ipod Movies

    Let's Say I have In My I Pod 5 songs Of Bon Jovi, If Those 5 Song Don't Have An Album Title, They All Apear In When I Press The Artist and then All. If I have More Then One title , let's say two of the five songs have different titles, the titles app