2013-07-17 103 views
1

我有下面這個select語句,我想用來更新另一個表tablex中的產品數量。我似乎無法弄清楚如何將此查詢中的產品編號與產品編號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' 

回答

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. 
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?

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標準也許?

+0

這將取代而不更新/添加quantity..I認爲它應該是'A.Quantity = A.Quantity + B.Quantity' –

+0

啊,好點,沒看到有問題的,更新。 –

0

我在猜你正在嘗試更新TableX中的大量行,因此我將建議一種方法來一次完成所有行,而不是一次執行一次。

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

您可能希望做這個的SalesOrderDetail一個子集,這很好,只是使用的是WHERE條款。

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) 
相關問題