TSQL: UPDATE with INSERT INTO SELECT FROM

前端 未结 7 2230
感情败类
感情败类 2021-02-08 05:11

so I have an old database that I\'m migrating to a new one. The new one has a slightly different but mostly-compatible schema. Additionally, I want to renumber all tables from

7条回答
  •  心在旅途
    2021-02-08 05:50

    Heh. I remember doing this in a migration.

    Putting the old_id in the new table makes both the update easier -- you can just do an insert into newtable select ... from oldtable, -- and the subsequent "stitching" of records easier. In the "stitch" you'll either update child tables' foreign keys in the insert, by doing a subselect on the new parent (insert into newchild select ... (select id from new_parent where old_id = oldchild.fk) as fk, ... from oldchild) or you'll insert children and do a separate update to fix the foreign keys.

    Doing it in one insert is faster; doing it in a separate step meas that your inserts aren't order dependent, and can be re-done if necessary.

    After the migration, you can either drop the old_id columns, or, if you have a case where the legacy system exposed the ids and so users used the keys as data, you can keep them to allow use lookup based on the old_id.

    Indeed, if you have the foreign keys correctly defined, you can use systables/information-schema to generate your insert statements.

提交回复
热议问题