tags:

views:

1540

answers:

3

Hello,

I have been looking for a while now but I can not find an easy solution for my problem. I would like to duplicate a record in a table, but of course, the unique primary key needs to be updated.

I have this query:

INSERT INTO invoices SELECT * FROM invoices AS iv WHERE iv.ID=XXXXX ON DUPLICATE KEY UPDATE ID = (SELECT MAX(ID)+1 FROM invoices)

the proble mis that this just changes the ID of the row instead of copying the row. Does anybody know how to fix this ?

Thank you verrry much, Digits

//edit: I would like to do this without typing all the field names because the field names can change over time.

A: 

You KNOW for sure, that the DUPLICATE KEY will trigger, thus you can select the MAX(ID)+1 beforehand:

INSERT INTO invoices SELECT MAX(ID)+1, ... other fields ... FROM invoices AS iv WHERE iv.ID=XXXXX
Ingo
yes, but I do not want to type all the other fields (there are more or less 20, and they might change over time). I do not want to change the code everytime the tablestructre changes.
Digits
You'll have to. You better make a script that generates the SQL statement from a list of fields. It's trivial.
Ingo
The only other alternative is to use an insert trigger (if mysql supports that).
Ingo
A: 

Hi I needed this as well; my solution was to use SQLYOG (free version) to export the desired record as SQL (creates an insert).

I then hand edited this to remove the id as this needs to be auto-generated and then copied the insert into SQLYog to execute it. This was painless. I guess plenty of other MySQL GUIs can do this as well.

This provides me with a record I can use for test purposes on a live system.

I now have this insert for reuse as well, as the table is rewritten daily.

zzapper
+1  A: 

The way that I usually go about it is using a temporary table. It's probably not computationally efficient but it seems to work ok! Here i am duplicating record 99 in its entirety, creating record 100.

CREATE TEMPORARY TABLE tmp SELECT * FROM invoices WHERE id = 99;

UPDATE tmp SET id=100 WHERE id = 99;

INSERT INTO invoices SELECT * FROM tmp WHERE id = 100;

Hope that works ok for you!

Alex