合并语句插入重复行?

Merge Statement inserting duplicate rows?

我一直在这上面花时间,但我似乎无法找到 MERGE 语句插入重复行的原因。这是我的 table。

TABLE <code>INVENTORY

ProductID  |   ProductName   |   ProductCode   |   Quantity   |   Location
1          |   Stabilo       |   Code123       |   3          |   Basement
2          |   Parker Pen    |   Code456       |   4          |   Basement

TABLE 收入库存</pre>

REQUESTNUMBER  |  ProductID    | ProductName  | ProductCode  | Quantity  | DeliveryLocation
Request123     |  2            | Parker Pen   | Code456      | 3         | Basement
Request123     |  3            | Eraser       | Code789      | 5         | Basement

一个请求号 = 多个项目,就像快餐外卖可以在一个交易号中包含多个订单。

当我 运行 这个查询...

MERGE INVENTORY as T1
USING INCOMINGSTOCKS AS T2
ON T1.ProductCode = T2.ProductCode
AND T2.REQUESTNUMBER = 'Request123' and T2.DeliveryLocation= 'Basement'
WHEN MATCHED THEN
UPDATE SET T1.Quantity = T1.Quantity + T2.Quantity
WHEN NOT MATCHED THEN
INSERT (ProductID, ProductName, ProductCode, Quantity, Location) 
VALUES (T2.ProductID, T2.ProductName, T2.ProductCode, T2.Quantity, T2.DeliveryLocation);


...它 returns 具有以下数据:

ProductID  | ProductName  |  ProductCode  |  Quantity  |  Location
Stabilo    | 1            |  Code123      |  3         |  Basement
Stabilo    | 1            |  Code123      |  3         |  Basement
Parker Pen | 2            |  Code456      |  7         |  Basement
Parker Pen | 2            |  Code456      |  4         |  Basement

"Eraser" 项甚至没有插入!它只复制了 Stabilo(它不在 INCOMINGSTOCKS table 中,添加了 Parker Pens (3+4) 的数量,这次又用它的初始数量重新插入了它。

拜托,有人可以帮助我吗?关于我的查询有任何见解或评论吗?有什么问题吗?

谢谢你!!!

有点不明白T2.DestinationLocation, T2.Location, USING INCOMING STOCKS AS T2

无论如何都这样尝试:

MERGE INVENTORY as T1
USING INCOMINGSTOCKS AS T2
ON T1.ProductCode = T2.ProductCode
and T2.REQUESTNUMBER = 'Request123' and T2.DeliveryLocation = 'Basement'
WHEN MATCHED THEN
UPDATE SET T1.Quantity = T1.Quantity + T2.Quantity
WHEN NOT MATCHED THEN
INSERT (ProductID, ProductName, ProductCode, Quantity, Location) 
VALUES (T2.ProductID, T2.ProductName, T2.ProductCode, T2.Quantity, T2.DeliveryLocation);

select * from INVENTORY