再会。我有3张桌子:
tblWarehouse产品 :
ProductID ProductName ProductCode Quantity
tblBranchProducts :
ProductID ProductCode ProductCode Quantity Location
tblStockMoves :
ProductID DestinationLocation Quantity ReferenceNumber
基本上,该过程是分支X从仓库Y请求产品。然后仓库Y创建一个请求订单(称为“ 库存移动” )并将请求存储在 tblStockMove中 。
说这种情况,我们有一个参考编号为XYZ的库存移动:
REFERENCE NO. | PRODUCT ID | DESTINATION | QTY | XYZ | 1 | BRANCH Y | 5 | XYZ | 2 | BRANCH Y | 6 |
(其中产品ID 1为可乐,产品ID 2为百事可乐。) 另一方面,分支X有此产品库存:
PRODUCT ID | PRODUCT NAME | PRODUCT CODE | QUANTITY | LOCATION | 1 | COKE | ABC123 | 6 | Branch X |
我目前正在尝试检查tblBranchProducts中是否存在tblStockMoves中的项目。
如果产品1存在,它将把tblStockMoves中的数量添加到tblBranchProducts中的当前数量。由于产品2是新商品,因此将其添加为新条目。
我在下面使用此查询,但到目前为止,它所做的只是在忽略(不插入)产品ID 2的同时更新产品ID 1的库存。
IF EXISTS (select ProductID, Location from tblBranchProducts a where Location = 'Branch X' and a.ProductID in (select b.ProductID from tblStockMoves b where b.ReferenceNumber = 'XYZ' and b.DestinationLocation = 'Branch X')) BEGIN UPDATE tblBranchProducts SET Quantity = a.Quantity + b.Quantity FROM tblBranchProducts a INNER JOIN tblStockMoves b ON a.ProductID = b.ProductID WHERE b.ReferenceNumber = 'XYZ' AND b.DestinationLocation = 'Branch X' END ELSE BEGIN INSERT INTO tblBranchProducts (ProductID, ProductName, ProductCode, Quantity, Location) SELECT b.ProductID, a.ProductName, a.ProductCode, b.Quantity, b.DestinationLocation FROM tblStockMoves b INNER JOIN tblWarehouseProducts a ON b.ProductID = a.ProductID WHERE b.ReferenceNumber = 'XYZ' AND b.DestinationLocation = 'Branch X'
其他详细信息(例如产品名称和产品代码)从tblWarehouseProducts中提取,然后插入到tblBranchProducts中。
谁能告诉我为什么我的查询仅更新产品1的现有库存而不插入产品2?
非常感谢您的回答!
您可以为所有不带的产品动态地执行此操作IF,只需添加所需的条件即可:
IF
/*will insert all the unmatched products*/ INSERT INTO tblBranchProducts (ProductID, ProductName, ProductCode, Quantity, Location) SELECT b.ProductID, a.ProductName, a.ProductCode, b.Quantity, b.DestinationLocation FROM tblStockMoves b inner join tblWarehouseProducts a on b.ProductID = a.ProductID LEFT JOIN tblBranchProducts c ON(a.productid = b.productid) where c.productid is null
和:
/*will update all the matching products*/ update tblBranchProducts a INNER join tblStockMoves b on a.productid = b.productid set a.quantity= b.qty