根据另一个选择更新表

时间:2013-07-17 20:08:36

标签: sql sql-server tsql

我在下面有这个选择声明,我想用它来更新另一个表tablex中的产品数量。我似乎无法弄清楚如何将此查询中的产品编号与productnumber tablex匹配,然后将此语句中找到的数量添加到tablex中的现有数量。

select 
    p.ProductNumber, sod.Quantity ,so.StateCode
from 
    SalesOrderDetail sod
right join 
    ProductAssociation pa on sod.ProductId = pa.ProductId
left join 
    Product p on pa.AssociatedProduct = p.ProductId
left join 
    SalesOrder so on so.SalesOrderId = sod.SalesOrderId
where 
    so.StateCode = '3'

5 个答案:

答案 0 :(得分:0)

您可以根据多个表进行更新,语法类似于

update tablex
set tablex.quantity = sod.Quantity
from tablex join product p on tablex.productnumber = p.ProductNumber
join... -- add the rest of your joins and conditions.

答案 1 :(得分:0)

你在找这个吗?

UPDATE tx SET tx.Quantity = tx.Quantity + sod.Quantity FROM 
from SalesOrderDetail sod
right join ProductAssociation pa on sod.ProductId=pa.ProductId
left join Product p on pa.AssociatedProduct=p.ProductId
left join SalesOrder so on so.SalesOrderId=sod.SalesOrderId
left join tablex tx on p.ProductNumer = tx.ProductNumber
where so.StateCode='3'

How can I do an UPDATE statement with JOIN in SQL?

答案 2 :(得分:0)

UPDATE的基本语法JOIN

UPDATE A
SET A.foo = B.bar
FROM TableA A
JOIN TableB B 
    ON A.col1 = B.colx

所以我相信你的目标是:

UPDATE A
SET A.Quantity = B.Quantity + A.Quantity
FROM Tablex A
JOIN (select p.ProductNumber, sod.Quantity ,so.StateCode
      from SalesOrderDetail sod
      right join ProductAssociation pa on sod.ProductId=pa.ProductId
      left join Product p on pa.AssociatedProduct=p.ProductId
      left join SalesOrder so on so.SalesOrderId=sod.SalesOrderId
      where so.StateCode='3'
      )B
   ON A.ProductNumber = B.ProductNumber

不确定您的StateCode如何影响其他JOIN标准?

答案 3 :(得分:0)

我猜你正在尝试更新TableX中的大量行,所以我建议一种方法一次完成所有行而不是一次一行。

update TableX
 set quantity = quantity +
 (select sod.quantity from SalesOrderDetail where sod.ProductId = TableX.ProductId)

您可能希望在SalesOrderDetail的子集上执行此操作,这没关系,只需使用WHERE子句即可。

答案 4 :(得分:0)

尝试

UPDATE tablex
SET Quantity= Quantity +
(SELECT sod.Quantity  FROM SalesOrderDetail sod
RIGHT JOIN ProductAssociation pa ON sod.ProductId=pa.ProductId
LEFT JOIN Product p ON pa.AssociatedProduct=p.ProductId
LEFT JOIN SalesOrder so ON so.SalesOrderId=sod.SalesOrderId
WHERE so.StateCode='3' AND p.ProductNumber=Tablex.productnumber)