首页 > 解决方案 > 如何在 SQL 中逐行顺序更新 2 个表

问题描述

我需要根据彼此的数据并行更新两个表。

下面是两个表的表结构。

产品表:

ProductId | ProductQuantity | Min Price | Max Price    
----------+-----------------+-----------+----------
1         | 122             | 58        | 585    
2         | 548             | 45        | 856

订单表:

Order ID | ProductID | ProductOrderQuantity |OfferPrice | OrderProcessDate | Status     
---------+-----------+----------------------+-----------+------------------+--------
1        | 2         |  35                  |  75       | Null             | Placed    
2        | 1         | 752                  | 258       | Null             | Placed

在以下情况下,我需要StatusOrder表格更新为“确认/拒绝”:

  1. ProductOrderQuantity应该小于表ProductQuantityProduct

  2. OfferPrice应该在Min Price和之间Max Price

  3. 如果两个条件都匹配,则StatusOrder表中Confirm/Reject更新OrderProcessDate为处理日期

此更新应按顺序对订单表中的每一行进行,并且一旦行中的状态更新为“已确认”,则立即更新ProductQuantityProductQuantity - ProductOrderQuantity

标签: sqlsql-serversql-update

解决方案


你可以检查使用

select 'OK'
FROM Order
INNER JOIN Product ON Product.ProductId = Order.ProductId
WHERE order.ProductOrderQuantity < Product.ProductQuantity
  AND order.OfferPrice between Product.min_price and Product.Max_price

最终您可以尝试在 JOIN 中使用更新来检查条件

update Order 
SET status = "Confirm/Reject",
    OrderProcessDate =  GETDATE()
FROM Order
INNER JOIN Product ON Product.ProductId = Order.ProductId
WHERE order.ProductOrderQuantity < Product.ProductQuantity
  AND order.OfferPrice between Product.min_price and Product.Max_price

推荐阅读