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

前端 未结 11 552
猫巷女王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:37

    I know my answer is late to the party. But the way i solved is bit different than all the answers.

    I had a situation, i need to clone a row in a table except few columns. Those few will have new values. This process should support automatically for future changes to the table. This implies, clone the record without specifying any column names.

    My approach is to,

    1. Query Sys.Columns to get the full list of columns for the table and include the names of columns to skip in where clause.
    2. Convert that in to CSV as column names.
    3. Build Select ... Insert into script based on this.

    
    declare @columnsToCopyValues varchar(max), @query varchar(max)
    SET @columnsToCopyValues = ''

    --Get all the columns execpt Identity columns and Other columns to be excluded. Say IndentityColumn, Column1, Column2 Select @columnsToCopyValues = @columnsToCopyValues + [name] + ', ' from sys.columns c where c.object_id = OBJECT_ID('YourTableName') and name not in ('IndentityColumn','Column1','Column2') Select @columnsToCopyValues = SUBSTRING(@columnsToCopyValues, 0, LEN(@columnsToCopyValues)) print @columnsToCopyValues

    Select @query = CONCAT('insert into YourTableName (',@columnsToCopyValues,', Column1, Column2) select ', @columnsToCopyValues, ',''Value1'',''Value2'',', ' from YourTableName where IndentityColumn =''' , @searchVariable,'''')

    print @query exec (@query)

提交回复
热议问题