简体   繁体   English

如何执行SELECT语句中的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. 对于我的DB课程,我有一个表:lab4Central,其列为:productid,description和plantid,工厂QRO的ID为1000,例如:12799,“产品12799”,1000。工厂SLP的ID为2000。 ,例如:29665,“产品29665”,2000。

I have to add new registers for other 2 plants: GDA and MTY. 我必须为其他2个工厂添加新的寄存器:GDA和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: 对于GDA,寄存器与工厂QRO相同,但是它已调整了productid + 20000,对于MTY相同,但具有SLP寄存器,因此最后看起来像:

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. 正如您所看到的,对于GDA而言,该寄存器与QRO中的寄存器相同,但与另一个Plantid相同,我们在productid中添加了20000,对于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. 但这只是一个选择,我不知道如何执行insert语句,因此它将数据插入表中。

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. 可能需要进行调整以适合您的数据,但是基本思想是编写SELECT语句,该语句为您提供了要插入到表中的结果集。

It can very well be a trick to generate INSERT statements that then manually are executed, maybe in batches of circa 100 lines. 生成INSERT语句,然后手动执行,可能是大约100行的批处理,这是一个很好的技巧。

Otherwise one would do an INSERT ... SELECT statement. 否则,将执行INSERT ... SELECT语句。 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 假设您要将选择结果插入到ProductId,Description和your_col_fro_3000列中,则可以使用INSERT SELECT

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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