1

我在存储过程中编写了以下代码,但它没有按我的预期工作

UPDATE  dbo.products
SET     stock = t.totalquantity
FROM    dbo.products
    INNER JOIN ( SELECT accountdetail.itemnumber ,
                        SUM(accountdetail.quantity + products.stock) totalquantity
                 FROM   accountdetail ,
                        products
                 WHERE  accountdetail.orderid = @accountorderid
                        AND dbo.products.itemnumber = accountdetail.itemnumber
                 GROUP BY accountdetail.itemnumber
               ) t ON dbo.products.itemnumber = t.itemnumber

如果只有 1 个带有数量的商品编号,则代码可以正常工作,但如果有 2 个带有数量的相同商品编号,则结果最终不正确

例如

  • 产品.库存 = 4
  • accountdetail.duantity = 2 from one itemnumber

  • products.stock = 6 - 这是正确的

  • 产品.库存 = 4

  • accountdetail.duantity = 2 from 两个 itemnumbers 相同

  • products.stock = 12 - 这是不正确的,我需要帮助来了解出了什么问题。

先感谢您。

4

2 回答 2

1

这应该解决它。

取出()中的产品

你在 () 之外加入吗

UPDATE dbo.products
SET    stock = t.totalquantity + stock
FROM   dbo.products
    INNER JOIN ( SELECT accountdetail.itemnumber ,
                        SUM(accountdetail.quantity) totalquantity
                 FROM   accountdetail
                 WHERE  accountdetail.orderid = @accountorderid
                 GROUP BY accountdetail.itemnumber
               ) t ON dbo.products.itemnumber = t.itemnumber
于 2013-09-04T17:44:46.453 回答
0

试试这个查询

with cte as (
   select a.itemnumber, sum(a.quantity) as totalquantity
   from accountdetail as a
   where a.orderid = @accountorderid
   group by a.itemnumber
)
update dbo.products set
    stock = stock + t.totalquantity
from dbo.products as p
    inner join cte as t on c.itemnumber = p.itemnumber
于 2013-09-04T17:45:18.983 回答