Inserting existing records to table and getting new identity ID for each row

I have an issue that I inherited where I need to insert some data to  12 tables related by FK  for about 40 records to an existing database through TSQL, SSIS is not an option..
Essentially the situation is that many weeks ago someone deleted a bunch of data and I cant do a restore of the database as new data has been entered so I need to "reconstruct" the data and reinsert it back. I cant just reinsert the data with the
same Primary keys as they are autogenerated. I restored a backup of the database taken prior to the deletion and have got all of my data I need loaded to temp tables. Now the issue I am running across is how to insert my "Main" table data row by
row and get the new identity and then update the corresponding row to the source temp table so that it can be used for the next 11 tables that need that Foreign Key.

How do I loop through the 40 records I am attempting to insert into the "Parent" table though?
You don't. That is, you don't loop.
You do:
MERGE target t
USING source s ON 1 = 0
WHEN NOT MATCH BY TARGET THEN
   INSERT (col1, col2, ...)
      VALUES(col1, col2, ...)
OUTPUT (t.JobId, s.JobId) INTO @idmap(newid, oldid)
UPDATE source
SET    newjobdid = i.newid
FROM   source s
JOIN   @idmap i ON s.jobid = i.jobid
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • How cna I deactivate multiple CS products and get new activation keys for them?

    I need to know how to deactivate all active installs of a given CS product and serial #, then get new activation keys for the same product.  I realize this is a question only an Adobe rep can answer, but online chat is closed and the phone support line is completely useless, so I have to ask here.
    -- Jon W. 

    you'll need to contact adobe support to reset your activation count for each product if you are unable to do that yourself, http://helpx.adobe.com/x-productkb/global/service1.html
    you will not get or need a new activation key.  your original one will still work for cs3 and later.

  • Find out and get the bit value for each pixel in image

    i use 16bit image. the image is 200x200 pixels. i need to know what is
    the bit value for each pixel. example(0111111011111101).
    where i can see the bit value output. if somebody got the example surce code please send it to me.coz i need the bit value to find out how many RGB color that use in the image. thanks for ur help.

    How many logins do you have???

  • Trying to insert a table and getting a "While executing objectTag in Table.htm, a JavaScript error o

    trying to insert a table and getting a "While executing objectTag in Table.htm, a JavaScript error occurred." message appears.  how do I fix this?

    Try this Technote
    http://kb2.adobe.com/cps/405/kb405604.html
    Try step 4 here
    http://kb2.adobe.com/cps/405/kb405604.html#main_dat

  • Have field map to existing record in table by secondary key

    Let's say I have a person table and a code table.
    person.datastoreId
    person.name
    person.foreignKeyToCodeValue
    code.datastoreId
    code.codeValue
    code is a static lookup table. I want to persist a new Person object:
    personObject.name = whatever
    personObject.code = something
    Obviously, person.code is mapped in the mapping XML to the code.codeValue
    table.
    If I call makePersistent(personObject) it will create a new record in the
    code table, right? if codeValue had a unique constraint on it, is there a
    way, so that it would automatically associate that person.codeValue with
    the existing record instead of creating a new one?
    I know I could do a query to get the codeValue object first and assign
    personObject.code to that, but I'm wondering if there is a way to avoid
    that.
    Thanks!
    Joel Shellman

    Joel-
    You will need to implement this sort of singleton pattern yourself.
    The most common way would be to do something like:
    public class Person
    private Code code;
    public void setCodeValue (String value)
    try
    code = (Code)JDOHelper.getPersistenceManager (this).
    getObjectById (new CodeValue.ID (value), false);
    catch (ObjectNotFoundException none)
    // none exists; make a new one with the specified key
    code = new Code ();
    code.setPrimaryKeyField (value);
    In article <bvtod5$nkp$[email protected]>, Joel Shellman wrote:
    Let's say I have a person table and a code table.
    person.datastoreId
    person.name
    person.foreignKeyToCodeValue
    code.datastoreId
    code.codeValue
    code is a static lookup table. I want to persist a new Person object:
    personObject.name = whatever
    personObject.code = something
    Obviously, person.code is mapped in the mapping XML to the code.codeValue
    table.
    If I call makePersistent(personObject) it will create a new record in the
    code table, right? if codeValue had a unique constraint on it, is there a
    way, so that it would automatically associate that person.codeValue with
    the existing record instead of creating a new one?
    I know I could do a query to get the codeValue object first and assign
    personObject.code to that, but I'm wondering if there is a way to avoid
    that.
    Thanks!
    Joel Shellman--
    Marc Prud'hommeaux [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • BDC for existing record in table control

    Hi,
    I have a requirement to change existing records in table control through BDC. Is there any way I can choose the respective record from Table Control through BDC dynamically.
    Regards
    Akash

    /J4I/015PER, this transaction is used for adding permits to Operation in WEC. It has list of operations in Table Control. Permit can be added for choosing the operation from table control.
    Our custom program is designed to add permits for the operation. So if I have to use the above transaction for adding permits, then first I have to choose the correct operation from the table control and then add permit.

  • Inserting multiple records to table in web dynpro

    I am inserted single record in table created in web
    dynpro view. If i insert the second record then the
    first record has been overwritten. How to display
    all rows that i was inserted without overwritting..
    Can any one send me the coding???

    method ONACTIONINSERT .
    *getting inputs
        DATA lo_nd_district TYPE REF TO if_wd_context_node.
        DATA lo_el_district TYPE REF TO if_wd_context_element.
        DATA ls_district TYPE wd_this->element_district.
        DATA lv_district_txt LIKE ls_district-district_txt.
      navigate from <CONTEXT> to <DISTRICT> via lead selection
        lo_nd_district = wd_context->get_child_node( name = wd_this->wdctx_district ).
      get element via lead selection
        lo_el_district = lo_nd_district->get_element(  ).
      get single attribute
        lo_el_district->get_attribute(
          EXPORTING
            name =  `DISTRICT_TXT`
          IMPORTING
            value = lv_district_txt ).
    *inserting into table
    DATA lo_nd_table TYPE REF TO if_wd_context_node.
      DATA lo_el_table TYPE REF TO if_wd_context_element.
      DATA ls_table TYPE wd_this->element_table.
      DATA lv_name LIKE ls_table-name.
    navigate from <CONTEXT> to <TABLE> via lead selection
      lo_nd_table = wd_context->get_child_node( name = wd_this->wdctx_table ).
    get element via lead selection
      lo_el_table = lo_nd_table->get_element(  ).
    get single attribute
      lo_el_table->set_attribute(
        EXPORTING
          name =  `NAME`
      "  IMPORTING
          value = lv_name_txt )."lv_name
    *LIKEWISE I INSERTED AGE COLUMN TOO.

  • IPhone 4s.used to get swoosh sound every time I got an email.  Now I don't and I have to open email for it to connect and get new messages.  What do I do?

    iPhone 4s.used to get swoosh sound every time I got an email.  Now I don't and I have to open email for it to connect and get new messages.  What do I do?

    Once you purchase or download an app it will always be associated with the Apple ID used to download it. When that app requires and update you must use the Apple ID and password used to download it in the first place. The only way around this is to delete the apps the require the old Apple ID and download or purchase them again with the new Apple ID.

  • I have the iphone 5 and when I try and get new apps it says an unknown error has occurred.  The password is correct

    I have the iphone 5 and when i try and get new apps it says an unknown error has occured.  The password is correct.  A couple of times i have seen a little glitch in small lines of pixels across the screen.  Started happening about the same time.....????

    Did you read my response in your first post? Look here.
    https://discussions.apple.com/thread/4912178

  • :new., lob columns and after insert ... for each row trigger

    I'm having this little problem with
    my update/insert triggers and lob columns.
    I have this little trigger:
    CREATE OR REPLACE TRIGGER BLOB_DATA_INSERT
    AFTER INSERT ON BLOB_DATA
    FOR EACH ROW
    BEGIN
    INSERT INTO BLOB_DATA_CHANGE VALUES(CHANGE_SEQ.NEXTVAL, 'I', :NEW.ID,:NEW.DATA);
    END;
    Which works except when the DATA column
    is a BLOB or CLOB (There is no data in :NEW.DATA. I even tried some of the DBMS_LOB package procedures)
    The one thing that is different for the lob columns is that the application updating
    the data is using a bind statement with returning, like:
    INSERT INTO BLOB_DATA
    VALUES(:ID,EMPTY_BLOB())
    RETURNING DATA INTO :DATA;
    COMMIT;
    Thanks for any help

    I'm having this little problem with
    my update/insert triggers and lob columns.
    I have this little trigger:
    CREATE OR REPLACE TRIGGER BLOB_DATA_INSERT
    AFTER INSERT ON BLOB_DATA
    FOR EACH ROW
    BEGIN
    INSERT INTO BLOB_DATA_CHANGE VALUES(CHANGE_SEQ.NEXTVAL, 'I', :NEW.ID,:NEW.DATA);
    END;
    Which works except when the DATA column
    is a BLOB or CLOB (There is no data in :NEW.DATA. I even tried some of the DBMS_LOB package procedures)
    The one thing that is different for the lob columns is that the application updating
    the data is using a bind statement with returning, like:
    INSERT INTO BLOB_DATA
    VALUES(:ID,EMPTY_BLOB())
    RETURNING DATA INTO :DATA;
    COMMIT;
    Thanks for any help

  • Have a brand new itouch ttried loads of times to connect to my home wi-fi with no luck, called support they told me to take it back and get new one, same results have wi-fi sign on top but not really connected. help.

    new itouch won't connect to wi-fi, has wi-fi sign on top, but is not really connected, called apple support they told me to take it back and get new one, but same problem please help

    Test it on another network--like at McDonals. If it works there, you got an issue on your home network--like a router setting.
    Basic troubleshooting steps 
    17" 2.2GHz i7 Quad-Core MacBook Pro  8G RAM  750G HD + OCZ Vertex 3 SSD Boot HD 
    Got problems with your Apple iDevice-like iPhone, iPad or iPod touch? Try Troubleshooting 101
     In Memory of Steve Jobs 

  • Had to get new hard disk for my macbook. After installing snow leopard on new HD the computer only connects to free wifi at certain places and not others. Took it to genius bar (of course it worked find there!) they said it was fine. Not!

    Had to get new hard disk for my macbook. After installing snow leopard on new HD the computer only connects to free wifi at certain places and not others. Took it to genius bar (of course it worked find there!) they said it was fine. But problem persist.

    Hi there ricalimo,
    I would recommend taking a look at the troubleshooting steps in the article below. If the issue is location specific, than you may want to save the article so you can perform troubleshooting when you are experiencing trouble.
    Wi-Fi: How to troubleshoot Wi-Fi connectivity
    http://support.apple.com/kb/HT4628
    -Griff W. 

  • How do i get my account unlocked and get new security questions

    how do i get my account unlocked and get new security questions?

    You need to ask Apple to reset your security questions; ways of contacting them include clicking here and picking a method for your country, phoning AppleCare and asking for the Account Security team, and filling out and submitting this form.
    They wouldn't be security questions if they could be bypassed without Apple verifying your identity.
    (100996)

  • SQL merge and after insert or update on ... for each row fires too often?

    Hello,
    there is a base table, which has a companion history table
    - lets say USER_DATA & USER_DATA_HIST.
    For each update on USER_DATA there has to be recorded the old condition of the USER_DATA record into the USER_DATA_HIST (insert new record)
    - to have the history of changes to USER_DATA.
    The first approach was to do the insert for the row trigger:
    trigger user_data_tr_aiu after insert or update on user_data for each rowBut the performance was bad, because for a bulk update to USER_DATA, there have been individual inserts per records.
    So i tried a trick:
    Instead of doing the real insert into USER_DATA_HIST, i collect the USER_DATA_HIST data into a pl/sql collection first.
    And later i do a bulk insert for the collection in the USER_DATA_HIST table with stmt trigger:
    trigger user_data_tr_ra after insert or update on user_dataBut sometimes i recognize, that the list of entries saved in the pl/sql collection are more than my USER_DATA records being updated.
    (BTW, for the update i use SQL merge, because it's driven by another table.)
    As there is a uniq tracking_id in USER_DATA record, i could identify, that there are duplicates.
    If i sort for the tracking_id and remove duplicate i get exactly the #no of records updated by the SQL merge.
    So how comes, that there are duplicates?
    I can try to make a sample 'sqlplus' program, but it will take some time.
    But maybe somebody knows already about some issues here(?!)
    - many thanks!
    best regards,
    Frank

    Hello
    Not sure really. Although it shouldn't take long to do a test case - it only took me 10 mins....
    SQL>
    SQL> create table USER_DATA
      2  (   id      number,
      3      col1    varchar2(100)
      4  )
      5  /
    Table created.
    SQL>
    SQL> CREATE TABLE USER_DATA_HIST
      2  (   id      number,
      3      col1    varchar2(100),
      4      tmsp    timestamp
      5  )
      6  /
    Table created.
    SQL>
    SQL> CREATE OR REPLACE PACKAGE pkg_audit_user_data
      2  IS
      3
      4      PROCEDURE p_Init;
      5
      6      PROCEDURE p_Log
      7      (   air_UserData        IN user_data%ROWTYPE
      8      );
      9
    10      PROCEDURE p_Write;
    11  END;
    12  /
    Package created.
    SQL> CREATE OR REPLACE PACKAGE BODY pkg_audit_user_data
      2  IS
      3
      4      TYPE tt_UserData        IS TABLE OF user_data_hist%ROWTYPE INDEX BY BINARY_INTEGER;
      5
      6      pt_UserData             tt_UserData;
      7
      8      PROCEDURE p_Init
      9      IS
    10
    11      BEGIN
    12
    13
    14          IF pt_UserData.COUNT > 0 THEN
    15
    16              pt_UserData.DELETE;
    17
    18          END IF;
    19
    20      END;
    21
    22      PROCEDURE p_Log
    23      (   air_UserData        IN user_data%ROWTYPE
    24      )
    25      IS
    26          ln_Idx              BINARY_INTEGER;
    27
    28      BEGIN
    29
    30          ln_Idx := pt_UserData.COUNT + 1;
    31
    32          pt_UserData(ln_Idx).id     := air_UserData.id;
    33          pt_UserData(ln_Idx).col1   := air_UserData.col1;
    34          pt_UserData(ln_Idx).tmsp   := SYSTIMESTAMP;
    35
    36      END;
    37
    38      PROCEDURE p_Write
    39      IS
    40
    41      BEGIN
    42
    43          FORALL li_Idx IN INDICES OF pt_UserData
    44              INSERT
    45              INTO
    46                  user_data_hist
    47              VALUES
    48                  pt_UserData(li_Idx);
    49
    50      END;
    51  END;
    52  /
    Package body created.
    SQL>
    SQL> CREATE OR REPLACE TRIGGER preu_s_user_data BEFORE UPDATE ON user_data
      2  DECLARE
      3
      4  BEGIN
      5
      6      pkg_audit_user_data.p_Init;
      7
      8  END;
      9  /
    Trigger created.
    SQL> CREATE OR REPLACE TRIGGER preu_r_user_data BEFORE UPDATE ON user_data
      2  FOR EACH ROW
      3  DECLARE
      4
      5      lc_Row      user_data%ROWTYPE;
      6
      7  BEGIN
      8
      9      lc_Row.id   := :NEW.id;
    10      lc_Row.col1 := :NEW.col1;
    11
    12      pkg_audit_user_data.p_Log
    13      (   lc_Row
    14      );
    15
    16  END;
    17  /
    Trigger created.
    SQL> CREATE OR REPLACE TRIGGER postu_s_user_data AFTER UPDATE ON user_data
      2  DECLARE
      3
      4  BEGIN
      5
      6      pkg_audit_user_data.p_Write;
      7
      8  END;
      9  /
    Trigger created.
    SQL>
    SQL>
    SQL> insert
      2  into
      3      user_data
      4  select
      5      rownum,
      6      dbms_random.string('u',20)
      7  from
      8      dual
      9  connect by
    10      level <=10
    11  /
    10 rows created.
    SQL> select * from user_data
      2  /
            ID COL1
             1 GVZHKXSSJZHUSLLIDQTO
             2 QVNXLTGJXFUDUHGYKANI
             3 GTVHDCJAXLJFVTFSPFQI
             4 CNVEGOTDLZQJJPVUXWYJ
             5 FPOTZAWKMWHNOJMMIOKP
             6 BZKHAFATQDBUVFBCOSPT
             7 LAQAIDVREFJZWIQFUPMP
             8 DXFICIPCBCFTPAPKDGZF
             9 KKSMMRAQUORRPUBNJFCK
            10 GBLTFZJAOPKFZFCQPGYW
    10 rows selected.
    SQL> select * from user_data_hist
      2  /
    no rows selected
    SQL>
    SQL> MERGE
      2  INTO
      3      user_data a
      4  USING
      5  (   SELECT
      6          rownum + 8 id,
      7          dbms_random.string('u',20) col1
      8      FROM
      9          dual
    10      CONNECT BY
    11          level <= 10
    12  ) b
    13  ON (a.id = b.id)
    14  WHEN MATCHED THEN
    15      UPDATE SET a.col1 = b.col1
    16  WHEN NOT MATCHED THEN
    17      INSERT(a.id,a.col1)
    18      VALUES (b.id,b.col1)
    19  /
    10 rows merged.
    SQL> select * from user_data_hist
      2  /
            ID COL1                 TMSP
             9 XGURXHHZGSUKILYQKBNB 05-AUG-11 10.04.15.577989
            10 HLVUTUIFBAKGMXBDJTSL 05-AUG-11 10.04.15.578090
    SQL> select * from v$version
      2  /
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - ProductionHTH
    David

  • If you registrate one Apple ID for each iPhone/iPad, you'll get 5GB on iCloud for each Apple ID, right? I have two iPhones and one iPad  with the same Apple ID, why can't I get 5 GB fo each of them?

    If you registrate one Apple ID for each iPhone/iPad, you'll get 5GB on iCloud for each Apple ID, right? I have two iPhones and one iPad  with the same Apple ID, why can't I get 5 GB fo each of them?

    Actually, everyone missed one point, when a device is priced, the cost of icloud storage space for that device is also included in it that is why they are able to give you 5gb each for each user ID, in nutshell there is nothing free coming with apple device purchase, it is paid for.  What they are trying by giving only 5gb per user ID irrespective of the number of devices used is pure broadlight looting, they take money from you when you buy each device and give you nothing, This is a case of goods and services bought but not fully deliverd ie apple can be suied for discreminatory treatment towards it's users. I wonder why no one tried this yet in America where everyone sue everyone for petty things..... there is no one to take up this issue? . if tim got any love for the guys who shell out money for the devices his company makes, he should be implimenting this as priority before someone wake up from sleep and sue him.

Maybe you are looking for

  • F4580

    - Windows 8.1 - Deskjet F4580 - Using HP AiO Printer remote and Hp Scan and Capture Problem: I have a problem with connect my printer wireless. It means I connet it. I can print wireless. But I can't take a scan.  In win7 was a special app for my pri

  • HT4235 I have tried everything previously suggested and I cannot get my laptop to recoginze my Apple Devices since the latest Windows 8 update!

    Here is the result of my iTunes Diagnostics Report. Please HELP! Microsoft Windows 8 x64 Home Premium Edition (Build 9200) Hewlett-Packard HP Pavilion g6 Notebook PC iTunes 11.1.5.5 QuickTime 7.7.4 FairPlay 2.5.16 Apple Application Support 3.0.1 iPod

  • No update, no payment

    As of today I am not paying my Verizon bill until my Nexus has the 3 latest updates installed. If Verizon doesn't like, they can *** << Comment removed to comply with Verizon Wireless Terms of Service  >> Message was edited by: Verizon Moderator

  • I've had it, contacting PSC

    Today is the 8th time this month my service is out. No service on November 1,2,3,4,5,6,16 & now the 18th. Customer support is extremely limited, if the answer is not on their list of steps, they have no idea. I have had intermittent outages for 3 yea

  • Question about unit conversion for BAPI_PO_CREATE1...

    Hello Experts, How do we bypass/supress the unit conversion in BAPI 'BAPI_PO_CREATE1'? Because what is happening right now is for example, I input in 88CV it will convert it to 'EA' as this is defined as the PO unit of measure. I want the 88 CV to be