Insert missing records

  • Hi,

    Ive messed up some data in a table but luckily I had it backed up.

    However I need to reinsert the missing data. I cant restore the backup table completely because Table1 has had new data inserted since.

    Looks something like this:

    Table1...................BackupTable

    Record1..................Record1

    Record2..................Record2

    Record4..................Record3

    Record5..................Record4

    As you can see, Table1 is missing record3

    So is there is quick sql that will insert all records from BackupTable into Table1 only IF they didnt exist previously?

    Assuming a unique field called ID.

    Regards

    Andy

  • Insert    Table1 (col1, col2 ....)

    Select    col1, col2....

    from      BackupTable b

    left join Table1 t

    on        t.id = b.id

    where     t.id IS NULL

    ..should do it.

    To check first, just run the select part without the insert, to see which rows you catch.

    /Kenneth

  • Actually I just solved it, but probably alot longer way around.

    I did

    DELETE FROM TableB WHERE EXISTS (SELECT * FROM TableA WHERE TableA.ID=TableB.ID)

    INSERT INTO TableB SELECT * FROM TableA

    I guess basically delete everything from tableB that already existed in the tableA. That should leave the remaining missing records that can be inserted.

    Kenneth your way was probably quicker.

    Many Thanks

    Andy

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply