How do you copy a record in a SQL table but swap out the unique id of the new row?

前端 未结 11 557
猫巷女王i
猫巷女王i 2020-11-30 19:09

This question comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifie

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 19:24

    I have the same issue where I want a single script to work with a table that has columns added periodically by other developers. Not only that, but I am supporting many different versions of our database as customers may not all be up-to-date with the current version.

    I took the solution by Jonas and modified it slightly. This allows me to make a copy of the row and then change the primary key before adding it back into the original source table. This is also really handy for working with tables that do not allow NULL values in columns and you don't want to have to specify each column name in the INSERT.

    This code copies the row for 'ABC' to 'XYZ'

    SELECT * INTO #TempRow FROM SourceTable WHERE KeyColumn = 'ABC';
    UPDATE #TempRow SET KeyColumn = 'XYZ';
    INSERT INTO SourceTable SELECT * FROM #TempRow;
    DELETE #TempRow;
    

    Once you have finished the drop the temp table.

    DROP TABLE #TempRow;
    

提交回复
热议问题