How do you copy a record in a SQL table but swap out the unique id of the new row?
Try this:
insert into MyTable(field1, field2, id_backup)
select field1, field2, uniqueId from MyTable where uniqueId = @Id;
Any fields not specified should receive their default value (which is usually NULL when not defined).
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).
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.