Insert records from a single table to two related tables

DB - 10G
OS - XP
We have many thousands of comma delimited records that we want to insert into a normalised table structure.
I have created a test dataset that can be found at the end of this post.
I have csv records that look like this;
donald, huey
donald, dewey
donald, louie
And I want the data to be inserted into two separate table like this;
table named PARENTS
pk parent_name
1  donald
Table named CHILDRENS
pk fk child_name
1  1 huey
1  2 dewey
1  3 louie
I constructed an insert statement that looks like this;
INSERT ALL
  INTO parents (parent_id, parent_name) VALUES (parents_seq.nextval, parent_name)
  INTO children (children_id, parent_id, child_name) VALUES(children_seq.nextval, parents_seq.nextval, child_name )
SELECT parent_name, child_name
  FROM sources;
And this resulted in the following;
Table named PARENTS
pk child_name
1  DONALD
2  DONALD
3  DONALD
Table named PARENTS
pk fk child_name
1  1  HUEY
2  2  DEWEY
3  3  LOUIE
Would anyone have any ideas on how I could accomplish this task?
This is some example data;
[code]
DROP SEQUENCE parents_seq;
DROP SEQUENCE sources_seq;
DROP SEQUENCE children_seq;
DROP TABLE sources;
DROP TABLE children;
DROP TABLE parents;
CREATE SEQUENCE PARENTS_SEQ MINVALUE 1 MAXVALUE 1000000000000000000000000000 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE;
CREATE TABLE PARENTS
( PARENT_ID      NUMBER(8) NOT NULL
, PARENT_NAME    VARCHAR2 (50 CHAR) NOT NULL
, CONSTRAINT     PARENTS_PK PRIMARY KEY (PARENT_ID)
create or replace
TRIGGER PARENTS_BI
BEFORE
  INSERT OR UPDATE ON PARENTS
  FOR EACH ROW BEGIN
  IF INSERTING THEN
    IF :NEW.PARENT_ID IS NULL THEN
      SELECT PARENTS_SEQ.nextval INTO :NEW.PARENT_ID FROM dual;
    END IF;
  END IF;
END;
CREATE SEQUENCE SOURCES_SEQ MINVALUE 1 MAXVALUE 1000000000000000000000000000 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE;
CREATE TABLE SOURCES
( SOURCE_ID      NUMBER(8) NOT NULL
, PARENT_NAME    VARCHAR2 (50 CHAR) NOT NULL
, CHILD_NAME    VARCHAR2 (50 CHAR) NOT NULL
, CONSTRAINT     SOURCES_PK PRIMARY KEY (SOURCE_ID)
create or replace
TRIGGER SOURCES_BI
BEFORE
  INSERT OR UPDATE ON SOURCES
  FOR EACH ROW BEGIN
  IF INSERTING THEN
    IF :NEW.SOURCE_ID IS NULL THEN
      SELECT SOURCES_SEQ.nextval INTO :NEW.SOURCE_ID FROM dual;
    END IF;
  END IF;
END;
INSERT INTO SOURCES (PARENT_NAME, CHILD_NAME) VALUES ('DONALD', 'HUEY');
INSERT INTO SOURCES (PARENT_NAME, CHILD_NAME) VALUES ('DONALD', 'DEWEY');
INSERT INTO SOURCES (PARENT_NAME, CHILD_NAME) VALUES ('DONALD', 'LOUIE');
Commit;
CREATE SEQUENCE CHILDREN_SEQ MINVALUE 1 MAXVALUE 1000000000000000000000000000 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE;
PROMPT *** CREATE TABLE ***
CREATE TABLE CHILDREN
( CHILDREN_ID    NUMBER NOT NULL
, PARENT_ID      NUMBER NOT NULL
, CHILD_NAME     VARCHAR2 (50 CHAR) NOT NULL
, CONSTRAINT     CHILDREN_PK PRIMARY KEY (CHILDREN_ID)
create or replace
TRIGGER CHILDREN_BI
BEFORE
  INSERT OR UPDATE ON CHILDREN
  FOR EACH ROW BEGIN
  IF INSERTING THEN
    IF :NEW.CHILDREN_ID IS NULL THEN
      SELECT CHILDREN_SEQ.nextval INTO :NEW.CHILDREN_ID FROM dual;
    END IF;
  END IF;
END;
[code]

Looks like this is one way of achieving it:
insert into parents (parent_name) select distinct parent_name from sources;
select *
  from parents;
PARENT_ID              PARENT_NAME                                       
1                      DONALD
insert into children (parent_id, child_name)
select p.parent_id, s.child_name
  from sources s
  join parents p
    on (s.parent_name = p.parent_name);
select *
  from children;
CHILDREN_ID            PARENT_ID              CHILD_NAME                                        
1                      1                      HUEY                                              
2                      1                      DEWEY                                             
3                      1                      LOUIE

Similar Messages

  • Inserting records from a txt file to a database table

    I would like to know how to insert records from a file (txt) to a database table through a java application?

    [BufferedReader |http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html] and PreparedStatement
    IO and JDBC

  • Inserting records from Infopath forms library to a SQL table

    Hi,
    I have a requirement where i need to populate records from a Infopath forms library to a SQL table in a database. We have written a console app to achive the same. However we are encountering performance issues when inserting records in the database. The
    way we retreive information from Infopath forms library is through a CAML query and then insert record by record in database. Is their a better and faster way to acheive this?
    Can someone pls help? 
    thanks,
    Anand
    Thanks and Regards, Anand R. Deshpande

    Hello Anand,
    Could you share you console application code? Also tell us when you face performance issue. I mean is there any problem in accessing infopath form or you are facing problem with only console application.
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • Inserting records from internal table to database table

    Hi all,
    i want to insert records from internal table to zDatabase table, can u plz guide me which statement is better in performance to insert the records.
    1) insert one by one record from internal table
    loop at itab.
    insert ztable from wa.
    endloop.
    2) insert total records at a time
    INSERT <dbtabname> CLIENT SPECIFIED FROM TABLE itab.
    or let me know if any other statement is there with high performance.
    i internal table contains nearly 40000 records.
    thanks.

    Hi,
    Insert the entire table at atime rather than a record so as to increase the performance.
    you can use INSERT <dbtabname> CLIENT SPECIFIED FROM TABLE itab.
    or
    MODIFY ZPRODUCT FROM TABLE GI_AFPO.
    Regards,
    Raj.

  • Insert records from report program into R3 table

    Hi
    I wanted to insert records from report program into R3 table.
    here is my code
    data : itab type standard table of zemp initial size 10 with header line.
    itab-EMPNO = '012'.
    itab-ENAME = 'XXXX'.
    itab-JOB = 'XXXX'.
    APPEND itab.
    insert ztable from table itab.
    but i am getting the following error
    the type of the data base table and work area/internal table "ITAB" are no unicode-converible.
    how can I insert records from report program into R3 table
    should I have to write move corresponding
    pls guide
    thanks
    manian

    Hi,
    itab-EMPNO = '012'.
    itab-ENAME = 'XXXX'.
    itab-JOB = 'XXXX'.
    APPEND itab.
    insert ztable from table itab.
    Do one thing
    Data : itab type table of ztable with header line.
    itab-EMPNO = '012'.
    itab-ENAME = 'XXXX'.
    itab-JOB = 'XXXX'.
    APPEND itab.
    insert ztable from table itab.
    error will resolve, then try to make structure similar to ZTABLE

  • Retrive last inserted  record  from database table

    Hi,
    some body inserting a record into table 'A' through some procedure/java program.i want to retrive the last inserted record from database table.records are not stored in order.Can any body help me.

    In general, unless you are storing a timestamp as part of the row or you have some sort of auditing in place, Oracle has no idea what the "first" or "last" record in a table is. Nor does it track when a row was inserted.
    - If you have the archived logs from the point in time when the row was inserted, you could use LogMiner to find the timestamp
    - If the insert happened recently (i.e. within hours), you may be able to use flashback query to get the value
    - If you're on 10g or later and the table was built with ROWDEPENDENCIES and the insert happened in the last few days and you can deal with a granularity of a few seconds and you don't need 100% accuracy, you could get the ORA_ROWSCN of the row and convert that to a timestamp.
    If this is something you contemplate needing, you need to store the data in the row or set up some sort of auditing.
    Justin

  • Insert record from one table to another with help of cursor

    Plz help!!!
    tables are - 1. country( country_id pk, country_name, region_id)
    2. a( country_id , country_name, region_id)
    table a data are
    1 a 1
    2 b 2
    3 c 3
    null d 4
    5 e 5
    6 f 6
    7 g 7
    insert record from table a to country table with help of cursor, insert all not null records.
    this procedure does not give correct result
    create or replace
    procedure amit as
    cursor c1 is select * from a;
    rw a%rowtype;
    begin
    open c1;
    fetch c1 into rw;
    while(c1%found)
    loop
    insert into countries values(rw.country_id,rw.country_name,rw.region_id);
    commit;
    fetch c1 into rw;
    if rw.country_id is null then
    fetch c1 into rw;
    end if;
    end loop;
    close c1;
    exception
    when others then
    dbms_output.put_line('exception name= '||rw.country_name);
    end;

    bluefrog wrote:
    You don't need cursor at all;
    create or replace procedure amit as
    begin
    insert into countries (Country_ID, Country_Name, Region_ID)
    (select a.Country_ID
    ,a.Country_Name
    ,a.Region_ID
    from a
    dbms_output.put_line('Rows inserted : ' || sql%rowcount);
    commit;
    end;
    Bluefrog you missed where clause. :)
       insert into countries (Country_ID, Country_Name, Region_ID)
       (select a.Country_ID
              ,a.Country_Name
              ,a.Region_ID
        from a
        where country_id is not null
    );

  • Master table with two child tables in ADF Framework

    Hi,
    I'm trying to implement single master with two detail tables using oracle adf framework of Jdev 11.1.1.4.0. I'm able to do single master-detail by using view link but unable to achieve nested details block i.e., master with nested child blocks.
    I created Query based view object of Master and two query based view objects as details. Then I created two view link for master with first child and another view link for master with second child. Even then in my data controls I see as two different components which is incorrect.
    Please let me know how to create a data control for an example shown below:
    Fruits [MASTER]
    --- Details of Fruits as adf table
    -- Apples [FIRST CHILD]
    ---- Details of Apples as adf table
    -- Oranges [SECOND CHILD]
    ---- Details of Oranges as adf table
    Regards,
    Amar.

    You need two viewLinks
    Fruits->Apples
    Fruits->Oranges
    Then in the data model you pick the Fruits entry that has:
    Fruits
    |--->Apples
    You stand on Fruits and you shuttle the Oranges to be under it from the left.
    If you'll use the default HR schema you'll see this type of relation for Employees:
    https://blogs.oracle.com/shay/entry/master_with_two_details_on_the

  • Insert records from one table to other table

    Hi,
    I want to insert all the records from table 1 which are not in table 2 into table2
    o/p
    insert into table2
    select * from table1
    where a.id!=b.id;
    Please let me know is there any way that I can populate the records

    insert
      into table2
      select  *
        from  table1
        where id not in (
                         select  id
                           from  table2
                        );SY.

  • Performance issue - insert records from db2 tables

    I have a table say emp in oracle database and i have the emp table in db2 database. My job is to pull all the records (million records) from db2 table to oracle emp table. My insert statement is like below. I am connecting to the db2 database using dblink.
    insert into emp
    select * from emp_db2, dept_db2
    where emp_db2.dno = dept_db2.dno
    and dept_db2.dno = 10;
    The statement is still running. How to improve the performance ?
    please suggest.
    thanks,
    Vinodh

    Vinodh2 wrote:
    1.how much is your select query is taking? 1 day over . still running.
    2.What is the row count from the query? 85632978 records
    3.Whats your expected completion time? 30 minutes
    I am not getting the explain plan because the query is still running.
    do as below
    SQL> set autotrace traceonly explain
    SQL> select sysdate from dual;
    Execution Plan
    Plan hash value: 1388734953
    | Id  | Operation      | Name | Rows     | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT |     |     1 |     2   (0)| 00:00:01 |
    |   1 |  FAST DUAL      |     |     1 |     2   (0)| 00:00:01 |
    -----------------------------------------------------------------

  • Insert data into two related tables in one transaction

    Hi all,
    I’ve got problem with developing functionality.
    Background:
    I’ve got two tables: OFFER_HEADER and OFFER_CONTENT
    For now, user has to insert and commit the OFFER_HEADER(single-row view), then content becomes reachable and OFFER_CONTENT(multi-row view) can be filled. It is being done by choosing record from PRODUCTS form and inserting values into OFFER_CONTENT. Product data can be modified on the CONTENT form canvas.
    My goal:
    I know that is not convenient way to implement the functionality. I want to insert all the data(header and content) in one transaction. What is the best way to do it?
    Thanks in advance,
    Best Regards,
    Bartek

    1. User is on the OFFER_CONTENT canvasOk
    2. User presses ‘+’ buttonOk
    3. On the screen is displayer PRODUCT list
    4. User set focus on desired product
    5. Using popup menu user choose ‘Add’ option
    6. PRODUCT list is being closedSo, the functionlatity is like a LoV?
    7. OFFER_CONTENT is being shown with set of information from the productOk, you would either take the values directly from the fields of the PRODUCT-list and copy them into the OFFER_CONTENT-fields, or you just get something like the PRODUCT-ID from your PRODUCT-list and use a SELECT to read the product-details into the OFFER_CONTENT-block
    8. User can then manually change desired elements of the recordOk.
    So, where do you have the need to do an INSERT in your scenario?

  • Update/Insert records from Oracle to MySQL

    Hi team, 
    My application will insert/update records into Oracle database, I need to sync all of records into MySQL database.  I designed a package to load data from Oracle to MySQL, the Oracle database use OLE DB component and MySQL database use ADO.NET.
    How to insert new records into MySQL? If the old record exists, we also need to replace with new record. I did some research, someone suggest to create a stage table to handle this scenario, but I have 14 tables in this case. How to handle this scenario
    with high performance? 
    If there is anything unclear, please let me know. 
    Thank you in advance. 

    Finally, I created 14 tables as same as in our MySQL database system with prefix "updated" , they are use to store the updated records from Oracle system. All of new records we add a flag, the "1" means insert a new record into the system,
    and the "0" means we should updated. So, I can use the conditional split component to split all of new records. The new records insert into the target table and the updated records insert into the "updated_table". Finally, we can add a
    SQL Script task to run a update script to sync all of records. 
    I don't use Lookup Transformation because we must use Cache
    Transform transformation in this case, the Cache connection manager to save the data to a cache file (.caw), it will hard to
    trace the history data in the future.  
    In addition, I recommend to use ODBC connection if somebody face the similar scenario with me, there is a bug  if we use ADO.NET to
    load data from Oracle to MySQL by using SSIS. For more information, please refer the MSDN document: http://blogs.msdn.com/b/mattm/archive/2009/01/07/writing-to-a-mysql-database-from-ssis.aspx
    @Arthur, thanks again for your input.  Have a nice day! :)

  • Insert pages from a single document multiple times

    I'm trying to create a simple program that I can use to display PDF files that I can use to play at the piano. I perform often, and need to create "play lists" from which I can pull all, or part of, a PDF file containing music and display it.
    I have it all working, except for one problem. I may need to "repeat" a section of a piece. I'm building up the play list by calling AcroPDDoc.InsertPages for each item in the play list. If a PDF file appears multiple times in the play list, when I call InsertPages, the call fails.
    In this code snippet, pdDoc is the main doc to which I'm adding pages. playList is a generic List of my own PlayList objects, and I need to iterate through all the items in the playList except the first one, which is already loaded.
    This code works great unless the fileName I specify has already been opened. The call to AcroPDDoc.Open succeeds just fine, but the call to pdDoc.InsertPages fails if the file has already had pages from it inserted. All other documents work fine. The documentation, of course, doesn't mention this.
            int insertPage = pdDoc.GetNumPages() - 1;
            for (int i = 1; i < playList.Count; i++)
              var newDoc = new AcroPDDoc();
              var item = playList(i);
              int startPage = 0;
              int endPage = 0;
              if (newDoc.Open(item.fileName))
                startPage = Math.Max(0, item.startPage);
                endPage = Math.Max(0, item.endPage);
                var totalPages = newDoc.GetNumPages;
                if (item.endPage < 0 || item.endPage > totalPages)
                  endPage = totalPages - 1;
                int numPages = (endPage - startPage) + 1;
                if (pdDoc.InsertPages(insertPage, newDoc, startPage, numPages, 0))
                  insertPage += numPages;
    So, the questions:
    1.) Is it possible to load pages from a single document multiple times?
    2.) Is there a better way to do this? (That is, loop through a list of file names, starting and ending page numbers, and add the documents to an existing document.)
    Any help appreciated! Thanks -- Ken

    Hi Ken,
    >The documentation, of course, doesn't mention this.
    The documentation does not state explicitly that you can't insert pages again from a PDDoc you open again and never close.
    But it mentions that you get references only from an already opened PDDoc.
    "...Opens the specified document. If the document is already open, it returns a reference to the already opened PDDoc. You must call PDDocClose() once for every successful open..."
    It doesn't state that you can't insert pages from a referenced PDDoc but it seems so.
    I would close the PDDoc within your for-loop after inserting pages and release newDoc.
    Regards
    Norbert

  • How to load data from a flat file to two different tables at a time.

    I am not aware of Sql Loader so Please any body suggest me that is there any way to load data from excel sheet to two different tables at a time its very urgent.
    with regards,
    Srinivas.R

    Read Utilities Guide from the Oracle Documentation Library. See
    <br>
    Oracle Database FAQs
    </br>

  • Urgent- How to separate bad records from load and put into a separate table

    We have an error handling requirement in ODI 11g from the client that whenever a bad record is encountered the execution flow shud not stop rather it shud separate those records into an error table so that at the end of the load we shud be left with all the records (except bad records) in the target table and those bad records shud be there in a separate error table.
    The definition of the bad records may include the size of a column or datatype mismatch between source and target table. How to implement this error handling strategy in ODI or is there any out of box solution that we can leverage Please Help.
    Thanks & Regards,
    SBV
    Edited by: user13133733 on Dec 23, 2011 4:45 AM

    Hi SBV,
    Please find my responses below,
    I have tried the steps suggested, however i have some doubts:
    1. What all data exceptions (e.g. primary key constraint violation etc.) are covered in this mechanism?Yes you can handle PK,FK, Check constraints violations etc., using CKM.
    2. If there is a column size mismatch between source and target table will this work? (I think not because i tried it and it'll give error before populating the I$ table, because I$ is created according to the source).
    You are right column size mismatches will not be captured as a part of default CKM property.
    Also i am getting an error in the creation of SNP_CHECK_TAB step. In my case ODI is by default making a query like "create table .SNP_CHECK_TAB" , now this dot (.) before SNP_CHECK_TAB is making it an invalid table name and hence this step is a warning (not an error), but in the next step (delete previous checksum) it is throwing an error as this step is also looking for .SNP_CHECK_TAB table which is not there.
    Please help me where the issue lies. I have NO idea why it is making that query by default I have freshly impoted the CKM Oracle and used it.
    This is coz there is no DEFAULT physical schema not defined at your target data server.
    Go to, Topology Manager-> Phy architecture -> <Your Technology>-> <Your target data server>-> expand, open up your physical schema and check DEAFULT.
    Thanks,
    Guru

Maybe you are looking for

  • Photos in iPhoto disappeared

    My photos in iPhoto have disappeared.  When attempting to open iPhoto, I get the message to choose a Library.  There is no library to choose.  How do I get my photos back?

  • Currency in GR

    Dear All, I have created a PO with currency USD, but in GR currency has come as INR, Please help me to know the reason and any setting (If i want same currency in GR) require for it. Thanks

  • I cannot able to save indesign document using sdk?

    hi,    i opened a indesign template using sdklayouthelper file and then update the text content in the template.After that i try to save(using sdklayouthelper file saveDocumentAs method) but i could not able to save a document as xxx.indd. pls,anyone

  • Openinig MS Office document from KM

    Hi! There is intresting situation. When user click to Excel document from KM it may takes him a very long time (10 minutes) when it opens. If Excel application is run before opening document from KM - opening completed immediately. Versions are: Netw

  • Mac OS Captive Runtime Filesize

    I have a simple one-screen Flex app that I'm using to test out the DatagramSocket class. Everything's working okay but when I build the application on Mac OS as a captive runtime the resulting app package is 169MB. This seems huge considering that th