【问题标题】:Merge Statement inserting duplicate rows?合并语句插入重复行?
【发布时间】:2017-03-27 00:25:15
【问题描述】:

对于我一直花时间在这方面的永恒,我似乎无法找到我的MERGE 语句插入重复行的原因。这是我的桌子。

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


...它返回以下数据:

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

“橡皮擦”项目甚至没有被插入!它只复制了 Stabilo(不在 INCOMINGSTOCKS 表中,添加了 Parker Pens (3+4) 的数量,并用其初始数量再次重新插入。

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

谢谢!!!

【问题讨论】:

  • 可能在 yoir WHERE 子句中检查:ISNULL (T1.ProductCode,'') != ''
  • 您发布的merge 声明甚至无效。你能发布你实际运行的那个吗?
  • @sstan 我已经更正了合并语句,谢谢。
  • 我仍然认为您实际上没有成功运行该语句。我收到 Incorrect syntax near the keyword 'WHERE'. 错误。
  • 抱歉,已将 where 替换为 and

标签: sql sql-server merge bulkinsert upsert


【解决方案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

【讨论】:

  • 对不起。我已经更正了查询。 T2.DestinationLocation and T2.Location are T2. DeliveryLocation.INCOMING STOCKS 中的空格删除为INCOMINGSTOCKS AS T2
猜你喜欢
  • 2020-04-05
  • 2018-07-22
  • 2016-02-25
  • 2013-01-16
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多