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 uniqueidentifier (guid). When I try this:
insert into MyTable
select * from MyTable where uniqueId = @Id;
I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).
I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.
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'
Once you have finished the drop the temp table.
If "key" is your PK field and it's autonumeric.
it will generate a new record, copying field1 and field2 from the original record
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,
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.
Replace the below table name with your table name
Replace the original identity field name with your PK field name
Replace the table names again (both target table name and source table name); edit your
where
conditionsYou can do like this:
There instead of 112 you should put a number of the maximum id in table DENI/FRIEN01P.
Try this:
Any fields not specified should receive their default value (which is usually NULL when not defined).