MERGE OUTPUT语句出现严重错误

时间:2013-05-22 17:40:22

标签: sql-server-2008 tsql stored-procedures etl

我收到严重错误 - 代码20,来自Merge声明,我不知道为什么。如果我删除OUTPUT $ action子句,并且按预期更新/插入目标表,MERGE运行正常。只要我将OUTPUT子句放入其中,或者将其作为简单的OUTPUT $操作或将其存储在表变量中并从中进行选择,就会导致错误级别为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

1 个答案:

答案 0 :(得分:5)

CTE目标中的计算列与输出子句相结合会导致致命错误。在Microsoft Connect

上提交错误