Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy rows from the same table and update the ID column

Tags:

sql

sql-server

I have the following table

alt text

I have inserted Product B to it and it gives me an ID of 15

Then I have the definition table which is as follows.

alt text

I want to select the ProductDefinition rows where ProdID = 14 and replicate the same and insert it for ProdID = 15 like the following

alt text

How to achieve this using SQL code?

like image 274
kalls Avatar asked Sep 22 '10 14:09

kalls


People also ask

How do you replicate rows in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

How do you UPDATE a column based on another column in a table?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.


1 Answers

INSERT INTO ProductDefinition (ProdID, Definition, Desc) SELECT   xxx, Definition, Desc FROM   ProductDefinition WHERE   ProdID = yyy 

The xxx is your new ProdID and the yyy is your old one. This also assumes that DefID is automagically populated on INSERT.

like image 83
Blrfl Avatar answered Sep 28 '22 06:09

Blrfl