views:

6492

answers:

7

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.

+11  A: 
AaronSieb
Awesome. Worked like a charm. It was so obvious once you wrote it out. Thanks!!
Kilhoffer
+1  A: 

Specify all fields but your ID field.

INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId)
SELECT FIELD2, NULL, ..., FIELD529, FIELD1
FROM MyTable
WHERE FIELD1 = @Id;
Scott Bevington
A: 

Do you maybe have a colleague working on the same issue? Because, a very similar question was asked just minutes ago.

Milan Babuškov
Ha! What a weird coincidence. I don't know that guy. I'm the only one working on this for my company. How funny...
Kilhoffer
+1  A: 
insert into MyTable (uniqueId, column1, column2, referencedUniqueId)
select NewGuid(), // don't know this syntax, sorry
  column1,
  column2,
  uniqueId,
from MyTable where uniqueId = @Id
Jeffrey L Whitledge
A: 

If "key" is your PK field and it's autonumeric.

insert into MyTable (field1, field2, field3, parentkey)
select field1, field2, null, key from MyTable where uniqueId = @Id

it will generate a new record, copying field1 and field2 from the original record

Eduardo Campañó
+1  A: 

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.

Matt Hinze
A: 

You can do like this:

INSERT INTO DENI/FRIEN01P SELECT RCRDID+112,PROFESION,NAME,SURNAME, AGE, RCRDTYP, RCRDLCU, RCRDLCT, RCRDLCD FROM FRIEN01P

There instead of 112 you should put a number of the maximum id in table DENI/FRIEN01P.

Denis Kutlubaev