使用update Query通过计算更新多行

时间:2017-09-26 06:50:58

标签: sql sql-server tsql sql-update

我有2张表“product”表

**prod_cat**     **prod_code**    **prod_name**   **prod_desc** **prod_price** **prod_stock**

MB01 MB01_micro ASU M5A_M华硕主题7500 enter image description here 45

PRO01 PRO01_01 INT_i3_7300英特尔酷睿i3处理器9313 5

和另一个表“cart”表

id cart_cust_id  cart_prod_id  cart_qty cart_prod_total cart_status
1   xxxx            ASU M5A_M     1        7500            NOT PAID
2   xxxx            INT_i3_7300   2        18626           NOT PAID

我需要的是根据“prod_stock”中的值减少“cart_qty”的查询或程序。有什么建议 ?

我还在链接中提供了2个表的屏幕截图。Screen shots of the tables

我的更新声明:

UPDATE product 
  SET prod_stock = ((SELECT cart_quantity 
                     FROM cart 
                     WHERE prod_code LIKE cart_prod_id 
                       AND cart_cust_id LIKE 'Gireesh.R.Pai@gmail.com' 
                       AND cart_status LIKE 'NOT PAID') - prod_stock) 

给出错误:

  

Msg 512,Level 16,State 1,Line 1 Subquery返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。声明已经终止。

2 个答案:

答案 0 :(得分:1)

您可以加入表格和

 ;WITH T AS(
    Select * FROM Product P 
    INNER JOIN CART C ON C.cart_prod_id = P.prod_code
    )
    Update T SET prod_stock = prod_stock - cart_quantity

答案 1 :(得分:1)

没有使用tempdb(更快的方式):

Nest.TypeMapping typeCo = null; // for the mapped Company type
Nest.IProperty propCoName = null;  // for the mapped Company Name property 

您可以添加WHERE子句:

UPDATE P
SET
    P.prod_stock = P.prod_stock - C.cart_quantity
FROM
    Product AS P
    INNER JOIN CART AS C ON (C.cart_prod_id = P.prod_code)