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

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

    Ok, I know that it's an old issue but I post my answer anyway.

    I like this solution. I only have to specify the identity column(s).

    SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;
    ALTER TABLE TempTable DROP COLUMN id;
    INSERT INTO MyTable_T SELECT * FROM TempTable;
    DROP TABLE TempTable;
    

    The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)

    I use SQL Server. You may want to use "CREATE TABLE" and "UPDATE TABLE" at row 1 and 2. Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.

    I edit my solution with the idéas from Michael Dibbets.

    use MyDatabase; 
    SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;
    ALTER TABLE #TempTable DROP COLUMN [IndexField]; 
    INSERT INTO [MyTable] SELECT * FROM #TempTable; 
    DROP TABLE #TempTable;
    

    You can drop more than one column by separating them with a ",". The :id should be replaced with the id of the row you want to copy. MyDatabase, MyTable and IndexField should be replaced with your names (of course).

    0 讨论(0)
  • 2020-11-30 19:32

    My table has 100 fields, and I needed a query to just work. Now I can switch out any number of fields with some basic conditional logic and not worry about its ordinal position.

    1. Replace the below table name with your table name

      SQLcolums = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE-NAME')"
      
      Set GetColumns = Conn.Execute(SQLcolums)
      Do WHILE not GetColumns.eof
      
      colName = GetColumns("COLUMN_NAME")
      
    2. Replace the original identity field name with your PK field name

      IF colName = "ORIGINAL-IDENTITY-FIELD-NAME" THEN ' ASSUMING THAT YOUR PRIMARY KEY IS THE FIRST FIELD DONT WORRY ABOUT COMMAS AND SPACES
          columnListSOURCE = colName 
          columnListTARGET = "[PreviousId field name]"
      ELSE
          columnListSOURCE = columnListSOURCE & colName
          columnListTARGET = columnListTARGET & colName
      END IF
      
      GetColumns.movenext
      
      loop
      
      GetColumns.close    
      
    3. Replace the table names again (both target table name and source table name); edit your where conditions

      SQL = "INSERT INTO TARGET-TABLE-NAME (" & columnListTARGET & ") SELECT " & columnListSOURCE & " FROM SOURCE-TABLE-NAME WHERE (FIELDNAME = FIELDVALUE)" 
      Conn.Execute(SQL)
      
    0 讨论(0)
  • 2020-11-30 19:36
    insert into MyTable (uniqueId, column1, column2, referencedUniqueId)
    select NewGuid(), // don't know this syntax, sorry
      column1,
      column2,
      uniqueId,
    from MyTable where uniqueId = @Id
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-30 19:41

    I'm guessing you're trying to avoid writing out all the column names. If you're using SQL Management Studio you can easily right click on the table and Script As Insert.. then you can mess around with that output to create your query.

    0 讨论(0)
提交回复
热议问题