Insert multiple rows using Cursors.

I am trying to insert rows into a table based on information from another table.
For example:
When Table 1: Num_Rows = 100 my proc will insert 100 rows into Table 2 with relevent data.
Do I need to use a Cursor and iterate through Num_Rows doing an INSERT each time? Is there a better way to do it other than using Cursors?
Rob.

It is not about using cursors or not using cursors. All SQLs wind up as cursors in the Oracle Shared Pool. So there is no such concept as not using cursors. Oracle needs to parse and compile and execute SQLs as cursors.
The issue is WHERE* you do the work?
Do you use the cursor (SQL) to do it for you? Or do you pull the data into another language, like PL or Java and process it there?
And the performance mantra in this case is a very fundemantal Maximize SQL and minimize PL/Java/etc+.
So do not do in PL/SQL what you can do in SQL only. It is a lot slower to pull data from the SQL engine into the PL engine. And then push that very same data from the PL engine back to the SQL engine. Like the following for example:
-- poor design, poor performance
for employee in (select e.* from emp e where e.deptid = 123 )
loop
  insert into tab2 values( employee.empid, employee.name );
end loop;You do not need to use PL (or Java) in this case. The SQL language is more than able to do this better and faster than any other language... as it is closer to the data.
So the following is far more optimal code. Instead of the above PL/SQL code, we can simply do it as:
-- optimal design: maximizing SQL and letting it to as much of the work as possible
insert into tab2 select e.empid, e.name from emp e where e.deptid = 123;

Similar Messages

  • Inserting multiple rows using a single Insert statement without using dual

    Hi all,
    i am trying to insert multiple rows using a single insert statement like the below one.
    The below one works fine..
    But is there any other change that can be done in the below one without using dual...
    insert all
    into ps_hd_samp (num1,num2) values (1,1)
    into ps_hd_samp (num1,num2) values (2,2)
    into ps_hd_samp (num1,num2) values (3,3)
    select 1 from dual;

    NiranjanSe wrote:
    Hi all,
    i am trying to insert multiple rows using a single insert statement like the below one.
    The below one works fine..
    But is there any other change that can be done in the below one without using dual...
    insert all
    into ps_hd_samp (num1,num2) values (1,1)
    into ps_hd_samp (num1,num2) values (2,2)
    into ps_hd_samp (num1,num2) values (3,3)
    select 1 from dual;
    SQL> create table ps_hd_samp (num1 number,num2 number);
    Table created.
    SQL> insert all
      2  into ps_hd_samp (num1,num2) values (1,1)
      3  into ps_hd_samp (num1,num2) values (2,2)
      4  into ps_hd_samp (num1,num2) values (3,3)
      5  select count(*)
      6  from ps_hd_samp;
    3 rows created.
    SQL> select * from ps_hd_samp;
          NUM1       NUM2
             1          1
             2          2
             3          3

  • Insert multiple rows from cursor to table

    Hi,
    I want to insert multiple rows retrieved from cursor to a table without looping the cursor till the end of cursor.
    I have the following structure, plz guide me.
    Create procedure procedure_name as
    cursor mycursor as
    select * from table1; --returns multiple row
    t_data table1%rowtype;
    begin
    fetch mycursor to t_data;
    loop
    exit when cursor not found;
    insert to table2
    end loop;
    end procedure;
    ===========================
    Now my cursor contains multiple records. I can iterate the records in loop and insert data to another table e.g table2 with same structure.
    But I want to insert the total data at a time without looping the cursor for each data.Please suggest how to do this ?
    Thanks in advance.

    You should be able to do it in a single statement (assuming table1 and table2 have the same columns/datatypes)
    insert into table2 (select * from table1);

  • Inserting multiple rows using a subquery getting ora error 0097 :Misssing )

    Iam getting ora :0097 missing right parenthesis
    insert into id_bfs_user_access_proj_racopy
    (user_name, project_id)
    ((Select user_name from id_bfs_user_access_cc Where cost_center_id in (select cost_center_id from ID_COST_CENTER_GROUPS_V where cost_center_group = 'Engineering')), 3)
    If i run below sql it is working fine can anyone help me in this
    insert into id_bfs_user_access_proj_racopy
    (user_name)
    (Select user_name from id_bfs_user_access_cc Where cost_center_id in (select cost_center_id from ID_COST_CENTER_GROUPS_V where cost_center_group = 'Engineering'))

    "how can it be valid since 3 is another column value and for user name we have to use entire sql"
    Did you try it? It is perfectly valid to select a constant as part of a SELECT statement, which is what 516945's solution does.
    SQL> CREATE TABLE t (id NUMBER, descr VARCHAR2(10));
    Table created.
    SQL> INSERT INTO t VALUES (1, 'One');
    1 row created.
    SQL> INSERT INTO t VALUES (2, 'Two');
    1 row created.
    SQL> COMMIT;
    Commit complete.
    SQL> SELECT id, descr, 'This is a constant string' const_str, 42 const_num
      2  FROM t;
            ID DESCR      CONST_STR                  CONST_NUM
             1 One        This is a constant string         42
             2 Two        This is a constant string         42John

  • How to update multiple rows using cursor.

    hi all,
    i want to update rows fetched by a cursor. it don't update the rows.
    and gives error:
    ORA-01002     fetch out of sequence
    here is the trigger.
    Declare
         alert_id ALERT := Find_Alert('on');
         alert_button NUMBER;
         var number :=10;
         v_al char(3);
         v_al_da date;
         s_date date;
         al_on number;
         to_time number;
         cursor rem is
              select re_about, alarm, alert_date
              from remind
              where alarm='ON' AND alert_date = :control.showdate
              for update;
    begin
         for rem_record IN rem LOOP
              Set_Alert_Property(alert_id, ALERT_MESSAGE_TEXT, rem_record.re_about);
              al_on := show_alert('ON');
              IF alert_button = ALERT_BUTTON1 THEN
              update remind
              set alarm = 'OFF'
              --where re_about = rem_record.re_about
              where current of rem;
              ELSE
              NULL;
              END IF;
              COMMIT;
         END LOOP;
    end;
    thanks
    Muhammad Nadeem
    Mardan

    thanks dear,
    i tried the following code outside the loop
    but the same problem.
    here is the code:
    Declare
         alert_id ALERT := Find_Alert('on');
         alert_button NUMBER;
         var number :=10;
         v_al char(3);
         v_al_da date;
         s_date date;
         al_on number;
         to_time number;
         cursor rem is
              select re_about, alarm, alert_date
              from remind
              where alarm='ON' AND alert_date = :control.showdate
              for update;
    begin
         for rem_record IN rem LOOP
         Set_Alert_Property(alert_id, ALERT_MESSAGE_TEXT, rem_record.re_about);
              al_on := show_alert('ON');
              IF alert_button = ALERT_BUTTON1 THEN
              update remind
              set alarm = 'OFF'
         where current of rem;
              ELSE
              NULL;
              END IF;
         END LOOP;
    if :SYSTEM.FORM_STATUS = 'changed' then
         COMMIT;
    end if;
    end;
    thanks
    Muhammad Nadeem

  • Insert multiple rows using sql at the same time

    I have searched a lot from the forum, but found nothing.
    There are two tables in oracle scheme: TableA(ID_A, column2,column3),
    TableB(ID_B, column2, column3); and TableA has multiply rows already, TableB is empty. TableB's ID_B has a
    Now I want to copy values from TableA.column2 and TableA.column3 to TableB.column2, TableB.column3.
    INSERT INTO SYSTEM_USER_GROUP (ID_user_group,ID_USER,ID_GROUP) values(((SELECT seq_system_user_group.NEXTVAL FROM DUAL),(SELECT U.ID_USER FROM SYSTEM_USER U),(SELECT U.ID_GROUP FROM SYSTEM_USER U)));
    ORA-00907: missing right parenthesis
    Any suggestion will be great appreciate!

    INSERT INTO SYSTEM_USER_GROUP (ID_user_group,ID_USER,ID_GROUP)
    (SELECT seq_system_user_group.NEXTVAL, ID_USER, ID_GROUP,
    FROM SYSTEM_USER)
    ORA-00936: missing expression
    ------------>>>
    I think that seq_system_user_group is a scheme level of oracle, so if you select it from a table, there will not work.
    Thank you all the same!
    Can i create that sequence as a column of one table? if that is the case, then my problem will be resolved.

  • How to insert multiple rows in a single shot using insert command?

    Hi,
    If we insert one row, we can use "insert into" command. I want to insert multiple rows into the table in a single shot. Is there any SQL command for insert multiple rows into the table?
    Plese give the solution.
    Thanks,
    chelladurai

    If you would like to do it with SQL, this would be one of the ways to achive it:
    SQL*Plus: Release 10.2.0.4.0 - Production on Fri Sep 25 10:12:59 2009
    Copyright (c) 1982, 2007, Oracle.  All Rights Reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Production
    With the Partitioning, Data Mining and Real Application Testing options
    SQL>
    SQL> desc leap
    Name                                      Null?    Type
    FIRST_PRICE                                        NUMBER(16,6)
    NEXT_PRICE                                         NUMBER(16,6)
    SQL>
    SQL> select * from leap;
    no rows selected
    SQL>
    SQL>
    SQL> !vi multirow_insert.sql
    SQL> !cat multirow_insert.sql
    insert into leap(first_price, next_price) values (1,2);
    insert into leap(first_price, next_price) values (3,4);
    insert into leap(first_price, next_price) values (5,6);
    SQL>
    SQL> @multirow_insert.sql
    1 row created.
    1 row created.
    1 row created.
    SQL> commit;
    Commit complete.
    SQL>
    SQL>
    SQL> select * from leap;
    FIRST_PRICE NEXT_PRICE
              1          2
              3          4
              5          6
    SQL>

  • Inserting Multiple Rows into Database Table using JDBC Adapter - Efficiency

    I need to insert multiple rows into a database table using the JDBC adapter (receiver).
    I understand the traditional way of repeating the statement multiple times, each having its <access> element. However, I am just wondering whether this might be performance-inefficient, as it might insert records one by one.
    Is there a way to ensure that the records are inserted into the table as a block, rather than record-by-record?

    Hi Bhavesh/Kanwaljit,
    If we have multiple ACCESS tags then what happens is that the connection to the database is made only once. But the data is inserted row by row.
    Why i am saying this?
    If we add the following in JDBC Adapter..logSQLStatement = true. Then incase of multiple inserts we can see that there are multiple
    <i>Insert into tablename(EMP_NAME,EMP_ID) VALUES('J','1000')
    Insert into tablename(EMP_NAME,EMP_ID) VALUES('J','2000')</i>
    Doesnt this mean that rows are inserted one by one?
    Correct me if i am wrong.
    This does not mean that the transaction is not guaranted. Either all the rows will be inserted or rolled back.
    Regards,
    Sumit

  • Inserting multiple rows into a table using a multiple-select list

    I'm trying to figure out how to take the output of a multiple-select list (":" separated list of values) and use that to update a table by inserting multiple rows based on the values. Is there a straight-forward way to do that in APEX?
    Thanks.
    Chris

    Hi Chris,
    I think this should give you what you need: Working with a Multiple Select List Item
    --Jennifer                                                                                                                                                                                                                                                                                                                                                                                                   

  • Inserting multiple rows into a table (using sequences)

    Hi!
    I want to insert multiple rows into a db table, but I don't know how.
    I know how to insert 1 row using a sequence:
    I put all the fields in the jsp form's page and in the submit page I put something like this:
    <jbo:Row id="myRow" datasource="ds" action="Update" rowkeyparam="MyRowKey" >
    <jbo:SetAttribute dataitem="*" />
    </jbo:Row>
    But how can I insert multiple rows like this:
    Id          Name
    1          ana
    2          monteiro
    3          maria
    Thanks!

    Hi Chris,
    I think this should give you what you need: Working with a Multiple Select List Item
    --Jennifer                                                                                                                                                                                                                                                                                                                                                                                                   

  • Inserting multiples rows into a table using function or procedure..

    How do i insert multiples rows into a table using function or procedure?
    Please provide me query..

    Use FORALL bulk insert statement...
    eg:
    procedure generate_test_data as
    type cl_itab is table of integer index by pls_integer;
    v_cl_itab cl_itab;
    type cl_vtab is table of varchar2(25) index by pls_integer;
    v_cl_vtab cl_vtab;
    type cl_dtab is table of date index by pls_integer;
    v_cl_dtab cl_dtab;
    begin
    for i in 1.. 100 loop
              v_cl_itab(i):= dbms_random.value(1,1000);
              v_cl_vtab (i):=dbms_random.string('a',20);
              v_cl_dtab (i):=to_date(trunc(dbms_random.value(2453737, 2454101)),'j');          
         end loop;
         forall i in v_cl_itab.first .. v_cl_itab.last
              execute immediate 'insert into test_order values( :n, :str , :dt ) ' using v_cl_itab(i), v_cl_vtab (i), v_cl_dtab (i);          
         commit;
    end;

  • How to insert multiple rows in oracle forms when using TEMPLATE FORM

    I got a case study on PO creation nd in that I have to insert multiple rows in form especally when PO creation screen is there.
    I tried by different syntaxes but its not working.I need correct syntax to insert the multiple rows in to the table in oracle forms

    Please Oracle EBS queries on EBS forums.

  • Want to insert multiple rows in table using EO

    Hi,
    I have one requirement where I need to insert multiple rows at once in table lets say Previous Employers.
    What I am trying to do is I have created few textinputboxes and getting there values and putting in HashMap.
    And manually inserting the rows to EO. I am not getting any error but the data is not populating in Table.
    here is the code snap ...please suggest!!
    public void updateKoelHrPreEmpVO(HashMap map)
    OADBTransaction txn = getOADBTransaction();
    //HashMap map = new HashMap();
    KoelHrPreEmpVOImpl empVO = getKoelHrPreEmpVO1();
    KoelHrPreEmpVORowImpl fetchedRow = null;
    int fetchedRowCount = empVO.getFetchedRowCount();
    RowSetIterator deleteIter = empVO.createRowSetIterator("deleteIter");
    if (fetchedRowCount > 0)
    if(txn.isLoggingEnabled(2))
    txn.writeDiagnostics(this,"Removing rows from KoelHrPreEmpVO :: Current count :: " + fetchedRowCount ,2);
    //System.out.println("Removing rows from KoelHrPreEmpVO :: Current count :: " +fetchedRowCount);
    deleteIter.setRangeStart(0);
    deleteIter.setRangeSize(fetchedRowCount-1);
    for (int i = 0; i < fetchedRowCount; i++)
    //System.out.println("Removing Row :: "+i);
    if(txn.isLoggingEnabled(2))
    txn.writeDiagnostics(this,"Removing row :: " + i ,2);
    fetchedRow = (KoelHrPreEmpVORowImpl)deleteIter.getRowAtRangeIndex(i);
    fetchedRow.remove();
    getTransaction().commit();
    deleteIter.closeRowSetIterator();
    if(empVO.getRowCount() == 0) {
    Row row = null;
    KoelHrPreEmpVORowImpl insertRow = null;
    empVO.first();
    if(txn.isLoggingEnabled(2))
    txn.writeDiagnostics(this,"Inserting rows to KoelHrPreEmpVO :: " ,2);
    try
    for(int i=1; i<=4; i++) {
    insertRow = (KoelHrPreEmpVORowImpl)empVO.createRow();
    insertRow.setEmployeeNumber(map.get("EmployeeNumber").toString());
    insertRow.setPersonId(new Number(map.get("PersonId").toString()));
    insertRow.setEmployer(map.get("Employer"+i+"").toString());
    insertRow.setStartDate(Date.toDate(map.get("StartDate"+i+"").toString()));
    insertRow.setEndDate(Date.toDate(map.get("EndDate"+i+"").toString()));
    insertRow.setEmployer(map.get("Designation"+i+"").toString());
    empVO.insertRow(insertRow);
    insertRow.setNewRowState(Row.STATUS_INITIALIZED);
    getTransaction().commit();
    catch(SQLException ex)
    ex.printStackTrace();
    Regards,
    Mukesh

    1. Pls check if the create() methos in EOImpl is in place, setting the primary key.
    2. Even though we insert values in this fashion , it only gets inserted if user performs any action, like manipulates some column. Pls check if there is any mechansm to make the row dirty ( as if done by user).
    Srikanth

  • Insert multiple rows question

    Hi!
    I need to insert multiple rows into a table with one run, but each row must have its unique id(PK). There is a sequence and a trigger
    in our database (11gR1) that get the next value. So, my question is: Is it possible to do a "bulk insert", maybe with a for loop cursor?
    Thanks for your feedback!

    user545194 wrote:
    Hi!
    I need to insert multiple rows into a table with one run, but each row must have its unique id(PK). There is a sequence and a trigger
    in our database (11gR1) that get the next value. So, my question is: Is it possible to do a "bulk insert", maybe with a for loop cursor?No need for a loop cursor, just insert the rows using an INSERT ... SELECT ... statement. If you have a row based trigger putting a sequence on the rows then it will allocated the id's accordingly.

  • How do I insert multiple rows from a single form ...

    How do I insert multiple rows from a single form?
    This form is organised by a table. (just as in an excel format)
    I have 20 items on a form each row item has five field
    +++++++++++ FORM AREA+++++++++++++++++++++++++++++++++++++++++++++++++++++
    +Product| qty In | Qty Out | Balance | Date +
    +------------------------------------------------------------------------+
    +Item1 | textbox1 | textbox2 | textbox3 | date +
    + |value = $qty_in1|value= &qty_out1|value=$balance1|value=$date1 +
    +------------------------------------------------------------------------+
    +Item 2 | textbox1 | textbox2 | textbox4 | date +
    + |value = $qty_in2|value= $qty_out1|value=$balance2|value=$date2 +
    +------------------------------------------------------------------------+
    + Item3 | textbox1 | textbox2 | textbox3 | date +
    +------------------------------------------------------------------------+
    + contd | | | +
    +------------------------------------------------------------------------+
    + item20| | | | +
    +------------------------------------------------------------------------+
    + + + SUBMIT + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Database Structure
    +++++++++++++++++
    + Stock_tabe +
    +---------------+
    + refid +
    +---------------+
    + item +
    +---------------+
    + Qty In +
    +---------------+
    + Qty Out +
    +---------------+
    + Balance +
    +---------------+
    + Date +
    +++++++++++++++++
    Let's say for example user have to the use the form to enter all 10 items or few like 5 on their stock form into 4 different textbox field each lines of your form, however these items go into a "Stock_table" under Single insert transaction query when submit button is pressed.
    Please anyone help me out, on how to get this concept started.

    Hello,
    I have a way to do this, but it would take some hand coding on your part. If you feel comfortable hand writing php code and doing manual database calls, specificaly database INSERT calls you should be fine.
    Create a custom form using the ADDT Custom Form Wizard that has all the rows and fields you need. This may take a bit if you are adding the ability for up to 20 rows, as per your diagram of the form area. The nice thing about using ADDT to create the form is that you can setup the form validation at the same time. Leave the last step in the Custom Form Wizard blank. You can add a custom database call here, but I would leave it blank.
    Next, under ADDT's Forms Server Behaviors, select Custom Trigger. At the Basic tab, you enter your custom php code that will be executed. Here you are going to want to put your code that will check if a value has been entered in the form and then do a database INSERT operation on the Stock_table with that row. The advanced tab lets you set the order of operations and the name of the Custom Trigger. By default, it is set to AFTER. This means that the Custom Trigger will get executed AFTER the form data is processed by the Custom Form Transaction.
    I usually just enter TEST into the "Basic" tab of the Custom Trigger. Then set my order of operations in the "Advanced" tab and close the Custom Trigger. Then I go to the code view for that page in Dreamweaver and find the Custom Trigger function and edit the code manually. It's much easier this way because the Custom Trigger wizard does not show you formatting on the code, and you don't have to keep opening the Wizard to edit and test your code.
    Your going to have to have the Custom Trigger fuction do a test on the submitted form data. If data is present, then INSERT into database. Here's a basic example of what you need to do:
    In your code view, the Custom Trigger will look something like this:
    function Trigger_Custom(&$tNG) {
    if($tNG->getColumnValue("Item_1")) {
    $item1 = $tNG->getColumnValue("Item_1");
    $textbox1_1 = $tNG->getColumnValue("Textbox_1");
    $textbox1_2 = $tNG->getColumnValue("Textbox_2");
    $textbox1_3 = $tNG->getColumnValue("Textbox_3");
    $date1 = $tNG->getColumnValue("Textbox_3");
    $queryAdd = "INSERT INTO Stock_table
    (item, Qty_In, Qty_Out, Balance, Date) VALUES($item1, $textbox1_1, $textbox1_2, $textbox1_3, $date1)"
    $result = mysql_query($queryAdd) or die(mysql_error());
    This code checks to see if the form input field named Item_1 is set. If so, then get the rest of the values for the first item and insert them into the database. You would need to do this for each row in your form. So the if you let the customer add 20 rows, you would need to check 20 times to see if the data is there or write the code so that it stops once it encounters an empty Item field. To exit a Custom Trigger, you can return NULL; and it will jump out of the function. You can also throw custom error message out of triggers, but this post is already way to long to get into that.
    $tNG->getColumnValue("Item_1") is used to retrieve the value that was set by the form input field named Item_1. This field is named by the Custom Form Wizard when you create your form. You can see what all the input filed names are by looking in the code view for something like:
    // Add columns
    $customTransaction->addColumn("Item_1", "STRING_TYPE", "POST", "Item_1");
    There will be one for each field you created with the Custom Form Wizard.
    Unfortunately, I don't have an easy way to do what you need. Maybe there is a way, but since none of the experts have responded, I thought I would point you in a direction. You should read all you can about Custom Triggers in the ADDT documentation/help pdf to give you more detailed information about how Custom Triggers work.
    Hope this helps.
    Shane

Maybe you are looking for