Search code examples
oracledynamicdynamic-sqlinsert-selectselect-insert

How to execute an INSERT that's in a SELECT statement?


for my DB course i have a table: lab4Central which columns are: productid, description and plantid, The plant QRO has and id = 1000, an example: 12799, 'Product 12799', 1000. and the plant SLP has an id = 2000, ex: 29665, 'Product 29665', 2000.

I have to add new registers for other 2 plants: GDA and MTY. For GDA the registers are the same of the plant QRO but it has tu adjust the productid + 20000, the same for MTY but with the registers of SLP so at the end it will look like:

Plant GDA: 329799, 'Product 32799', 3000.
plant MTY: 49665, 'Product 49665', 4000.

AS you can see for GDA the register is the same of the one in QRO but another plantid and we add 20000 to the productid, the same for MTY.

I code this which give me the correct values:

SELECT  'INSERT INTO LAB4CENTRAL VALUES('||(PRODUCTID+20000) || ',' || DESCRIPTION || ','|| 3000 ||');' FROM LAB4CENTRAL WHERE PLANTID=1000;

But it's just a select and i don't know how to execute the insert statement so it insert the data in the table.

hope you can help me.


Solution

  • assuming you want insert the select result in the column ProductId , Description and your_col_fro_3000 You could use a INSERT SELECT

        INSERT INTO LAB4CENTRAL(ProductID, Description, your_col_for_3000) 
        SELECT ProductID + 20000, 'Product' || (Productid + 20000), 3000 
        FROM LAB4CENTRAL 
        WHERE PlantID = 1000;