再会。我有3张桌子:
tbl仓库产品:
ProductID
ProductName
ProductCode
Quantity
tbl分公司产品:
ProductID
ProductCode
ProductCode
Quantity
Location
tbl股票走势:
ProductID
DestinationLocation
Quantity
ReferenceNumber
基本上,该过程是分支 X 向仓库 Y 请求产品。然后仓库 Y 创建一个请求订单(称为库存变动)并将请求存储在tbl库存移动.
对于本例,我们有一个参考编号为 XYZ 的库存变动:
REFERENCE NO. | PRODUCT ID | DESTINATION | QTY |
XYZ | 1 | BRANCH Y | 5 |
XYZ | 2 | BRANCH Y | 6 |
(其中 ProductID 1 是可口可乐,ProductID 2 是百事可乐。)
另一方面,X 分行有该产品的库存:
PRODUCT ID | PRODUCT NAME | PRODUCT CODE | QUANTITY | LOCATION |
1 | COKE | ABC123 | 6 | Branch X |
我目前正在尝试检查 tblStockMoves 中的项目是否存在于 tblBranchProducts 中。
如果产品 1 存在,它将把 tblStockMoves 中的数量添加到 tblBranchProducts 中的当前数量。产品 2 将作为新条目添加,因为它是新商品。
我正在使用下面的这个查询,但到目前为止,它所做的只是更新 ProductID 1 的库存,同时忽略(不插入)产品 ID 2。
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?
非常感谢您的回答!