Suppose I have the following tables:
----------------------------------------------------------------
| Products |
----------------------------------------------------------------
| id | ContractId | Name | Price | SpecialPriceId |
----------------------------------------------------------------
| 1 | 2002 | Apple | 1.10 | 300 |
| 2 | 2002 | Banana | 1.30 | 301 |
| 3 | 4500 | Orange | 1.30 | 302 |
| 4 | 2002 | Strawberry | 1.20 | 303 |
----------------------------------------------------------------
-----------------------
| SpecialPrice |
-----------------------
| id | Price | Vat |
-----------------------
| 300 | 0.80 | 6.00 |
| 301 | 0.90 | 6.00 |
| 302 | 0.90 | 6.00 |
| 303 | 0.85 | 6.00 |
-----------------------
I need to make a query that copies all the records from the Products
table where ContractId = 2002
. Those copies should be inserted as new records in the same table.
But, there is a tricky part. For each new Product
record, it should also create a copy of its correspondig SpecialPrice
record and INSERT that copy as new record as well.
So the end result should be this:
----------------------------------------------------------------
| Products |
----------------------------------------------------------------
| id | ContractId | Name | Price | SpecialPriceId |
----------------------------------------------------------------
| 1 | 2002 | Apple | 1.10 | 300 |
| 2 | 2002 | Banana | 1.30 | 301 |
| 3 | 4500 | Orange | 1.30 | 302 |
| 4 | 2002 | Strawberry | 1.20 | 303 |
| 5 | 2003 | Apple | 1.10 | 304 |
| 6 | 2003 | Banana | 1.30 | 305 |
| 7 | 2003 | Strawberry | 1.20 | 306 |
----------------------------------------------------------------
-----------------------
| SpecialPrice |
-----------------------
| id | Price | Vat |
-----------------------
| 300 | 0.80 | 6.00 |
| 301 | 0.90 | 6.00 |
| 302 | 0.90 | 6.00 |
| 303 | 0.85 | 6.00 |
| 304 | 0.80 | 6.00 |
| 305 | 0.90 | 6.00 |
| 306 | 0.85 | 6.00 |
-----------------------
What I can do is insert the copies of only the Products
.
INSERT INTO [Products]
(ContractId, Name, Price, SpecialPriceId)
SELECT (2003, Name, Price, SpecialPriceId)
WHERE ContractId = 2002
But I'd need to do something like this:
INSERT INTO [Products]
(ContractId, Name, Price, SpecialPriceId)
SELECT (2003, Name, Price, ( SELECT 'old' [SpecialPrice] record, then INSERT new record in [SpecialPrice] and use new ID here ))
WHERE ContractId = 2002
How can I do that in a query? Or some Stored Procedure logic will help. I don't really have a clue how to make this work,