Mahender
Mahender

Reputation: 5684

how to insert duplicate record with different custom generated primary key SQL Server

In SQL Server, is there any easy way to achieve below scenario?

In one of my table, I have around 20 columns and primary key field where we put generated number (it's not autogenerated field). For a reason, we wanted to duplicate a record of certain primary key value with different primary key value.

So this could be my table data (assume KEYxxx is primary key field)

KEY001  AA1  AA2 AA3 AA4 ... AA20
KEY002  AA1  AA2 AA3 AA4 ... AA20

I am trying to insert a new row with same data: KEY001 as KEY002

I have tried using this query here to do this, but failed, couldn't find a way to insert a new primary key value (KEY002) to this query.

INSERT INTO mytable (FIELD1, field2,...field20) 
    SELECT (FIELD1, field2,... field20) 
    WHERE field_primary_key = 'KEY001' 

Upvotes: 4

Views: 5027

Answers (1)

Milan Babuškov
Milan Babuškov

Reputation: 61198

Instead of specifying the PK column in the SELECT list, replace it with a literal value for the new key:

INSERT INTO mytable (FIELD_PK, field2,...field20) 
SELECT 'KEY002', field2,...field20
from mytable
where field_primary_key='KEY001'

Upvotes: 7

Related Questions