【问题标题】:Update multiple rows of a table having specific value in particular column equal to value calculated from two other tables更新表的多行,在特定列中具有特定值等于从其他两个表计算的值
【发布时间】:2013-04-07 19:07:14
【问题描述】:

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

的行

表 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

我想通过将 Quantity(从 Table 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

【问题讨论】:

  • 使用 SQL 数据库时,您应该始终考虑更新集合,而不是单行。这就是为什么 JW 下面的解决方案是有意义的。

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


【解决方案1】:

你可以直接更新TableC,加入TableBTableC就可以了。

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

【讨论】:

  • 让我试试这个,发布的问题是我正在尝试实现的高度简化版本,但我希望 Caption JW 将引导我正在下沉的船穿过 tsql 的风暴之海 ..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多