【问题标题】:SQL MERGE INSERT INTO not workingSQL MERGE INSERT INTO 不起作用
【发布时间】:2018-07-12 11:12:17
【问题描述】:

我在使用 SQL 中的 MERGE 语句时遇到问题。我尝试按照 Microsoft 的指南进行操作,但没有取得很大成功。

我希望代码更新它找到的任何匹配的行,并将不匹配的行插入到不同的表中。

我一直在使用下面的代码:

CREATE TABLE dbo.NotMatched
(ID INT , Year INT, Month INT, Quantity INT,   
 CONSTRAINT PK_Matched PRIMARY KEY CLUSTERED (ID));  
GO  

CREATE TABLE dbo.Updated
(ID INT , Year INT, Month INT, Quantity INT,   
 CONSTRAINT PK_Updated PRIMARY KEY CLUSTERED (ID));  
GO  

CREATE TABLE dbo.Staging
(ID INT , Year INT, Month INT, Quantity INT,   
 CONSTRAINT PK_Staging PRIMARY KEY CLUSTERED (ID));  
GO  

MERGE INTO dbo.Updated AS Target  
USING (SELECT ID, Year, Month, Quantity  
        FROM dbo.Staging AS stg) AS Source (ID, Year, Month, Quantity)  
 ON Target.ID = Source.ID  
WHEN MATCHED THEN  
UPDATE SET Target.Year = Source.Year, Target.Month = Source.Month, 
Target.Quantity = Source.Quantity
WHEN NOT MATCHED BY TARGET THEN  
INSERT (ID, Year, Month, Quantity) VALUES (Source.ID, Source.Year, Source.Month, Source.Quantity)  
OUTPUT $action INTO dbo.NotMatched (ID, Year, Month, Quantity);  

当我运行代码时,我收到以下错误:

INSERT 语句的选择列表包含的项目少于插入列表。 SELECT 值的数量必须与 INSERT 列的数量相匹配。

我看不到任何明显的错误,如果有人可以为我提供一些帮助,将不胜感激。

问候, 克里斯

【问题讨论】:

  • 你的代码不对,举个例子

标签: sql sql-server tsql merge


【解决方案1】:

$action ?这是做什么的?

应该是

OUTPUT inserted.ID, inserted.Year, inserted.Month, inserted.Quantity
INTO dbo.NotMatched (ID, Year, Month, Quantity);  

【讨论】:

  • 谢谢你,这有效。我正在使用docs.microsoft.com/en-us/sql/t-sql/statements/… 的示例,它们都包含$action。假设它是必需的。再次感谢!
  • $action - MERGE 的正常值。 "$action INTO dbo.NotMatched (ID, Year, Month, Quantity);"这个不正确
【解决方案2】:

来自您在 cmets 中引用的 MSDN 文档:

$action is a column of type nvarchar(10) that returns one of three values for each row: 'INSERT', 'UPDATE', or 'DELETE', according to the action that was performed on that row.

因此,这一行:

OUTPUT $action INTO dbo.NotMatched (ID, Year, Month, Quantity);  

不正确,因为它只有一个 nvarchar(10) 输入,但您尝试插入四列。

在使用$action 的示例中,它被插入到为描述操作的字符串设计的列中。

【讨论】:

  • 感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多