更新具有特定值的表的多行,该列等于从其他两个表计算的值

时间:2013-04-15 15:28:38

标签: sql sql-server tsql sql-server-2005 sql-update

我有三张桌子。我想更新列为Price=0

TableC

表A

StoreId rate
1       100   
2       200

表B

ProductId StoreId
11           1
22           2
30           1
40           1
67           2

表C

ProductID Quantity Price
11           20     0
22           30     6000
30           100    0 
40           200    0
67           370    0

我希望通过将数量(从表C中获得)乘以由TableB链接的Rate(从TableA获得)来更新Price = 0的TableC行

现在我的困惑是如果我必须更新TableC的单行

,方法将会起作用
declare @rate int,declare @qty int

select @rate =rate , @qty=quantity
from tableA a
inner join tableB b
   on a.storeId=b.storeId
inner join tableC c
   on b.productId=c,productId
--where c.productId=somevalue --one row returned
-- where c.Price=0  -- returns multiple row -- update wont work

1 个答案:

答案 0 :(得分:2)

您可以加入TableCTableB直接更新TableC

UPDATE  c
SET     c.Price = c.Quantity * a.Rate
FROM    TableC c
        INNER JOIN TableB b
            ON c.ProductID = b.ProductID
        INNER JOIN TableA a
            ON b.StoreID = a.StoreID
WHERE   c.Price = 0