合并语句插入重复的行?

时间:2016-11-13 04:28:20

标签: sql sql-server merge bulkinsert upsert

对于我一直在这方面花费时间的永恒,我似乎找不到为什么我的MERGE语句插入重复行的原因。这是我的表格。

TABLE INVENTORY

INVENTORY

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

TABLE INCOMINGSTOCKS

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

当我运行此查询时...

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);

“橡皮擦”项目甚至没有插入!它只复制了Stabilo(不在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 表中,添加了INCOMINGSTOCKS(3 + 4)的数量,并且这次用初始数量再次重新插入。

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

谢谢!!!

1 个答案:

答案 0 :(得分:1)

我有点不理解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