【发布时间】:2017-03-23 09:51:45
【问题描述】:
美好的一天。我有 3 张桌子:
tblWarehouseProducts:
ProductID
ProductName
ProductCode
Quantity
tblBranchProducts:
ProductID
ProductCode
ProductCode
Quantity
Location
tblStockMoves:
ProductID
DestinationLocation
Quantity
ReferenceNumber
基本上,流程是分公司 X 向仓库 Y 请求产品。仓库 Y 然后创建请求订单(称为 Stock Move)并将请求存储在 tblStockMove.
假设对于这种情况,我们有一个参考编号为 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 中。
如果 Product 1 存在,它会将 tblStockMoves 中的 Qty 添加到 tblBranchProducts 中的当前 Qty。产品 2 将作为新条目添加,因为它是新项目。
我在下面使用这个查询,但到目前为止,它所做的只是更新 ProductID 1 的库存,同时忽略(不插入)Product 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?
非常感谢您的回答!
【问题讨论】:
标签: sql sql-server insert-update