我从 Merge 语句中收到一个严重错误 - 代码 20,我不知道为什么。如果我删除 OUTPUT $action 子句并按预期更新/插入目标表,则 MERGE 运行良好。一旦我将 OUTPUT 子句作为简单的 OUTPUT $action 或将其存储在表变量中并从中选择,它就会导致错误级别 20。我使用两个 CTE 作为目标和源。不确定这是否会导致问题,但正如我所说,没有 OUTPUT 子句它可以正常工作。使用 SQL Server 2008。为了便于阅读,我在这里删除了大部分列。
USE [DM]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MergeMDATEST]
@InsertAuditKey INT = 10
,@UpdateAuditKey INT = 1
AS
SET NOCOUNT ON;
DECLARE @RowCounts TABLE (mergeAction varchar(20));
--------------------------------------------
--- CTEs to add in Binary_Checksum Calcs ---
WITH SourceQuery AS
(
SELECT TOP 100
[Company]
,[AccountNumber]
,BINARY_CHECKSUM([Company]) As [Checksum]
FROM #temptestMergeSource
)
,TargetTable AS
(
SELECT TOP 100
[Company]
,BINARY_CHECKSUM([Company]) As [Checksum]
FROM #temptestMergeTarget
)
MERGE TargetTable AS Target
USING SourceQuery As Source
ON (
Target.[AccountIndex] = Source.[AccountIndex]
AND Target.[CodeID] = Source.[CodeID]
AND Target.[GroupID] = Source.[GroupID]
)
WHEN MATCHED AND (Target.[Checksum] <> Source.[Checksum]) THEN
UPDATE SET
[AccountNumber] = Source.[AccountNumber]
,[AuditKey] = @UpdateAuditKey
WHEN NOT MATCHED THEN
INSERT (
[Company]
,[AuditKey]
)
VALUES (
Source.[Company]
,@InsertAuditKey
)
OUTPUT $action INTO @RowCounts;
SELECT * FROM @RowCounts
-----RowCounts returned for auditing
--SELECT
-- COUNT(CASE WHEN mergeAction = 'Insert' THEN 1 ELSE 0 END) As [INSERT]
-- ,COUNT(CASE WHEN mergeAction = 'Update' THEN 1 ELSE 0 END) As [UPDATE]
--FROM @RowCounts