简体   繁体   中英

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.

What you want is actually the opposite of what you wrote. Instead an Insert... Select... is probably what you are after.

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

That may need to be tweaked to fit your data, but the basic idea is to write a SELECT statement that gives you the result set that you then want to insert into the table.

It can very well be a trick to generate INSERT statements that then manually are executed, maybe in batches of circa 100 lines.

Otherwise one would do an INSERT ... SELECT statement. But that is not possible for the same table , hence this solution.

See also OUTPUT TO FILE or such (I do not know at this moment).

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM