8

我正在尝试学习如何使用 MERGE 运算符。以下代码正确编译:

    ALTER PROCEDURE moto.procPM_UpdateLines
@LineId As Int = null,
@LineName As Varchar(100),
@DeleteMe As Bit = 0
    AS
    BEGIN

    MERGE moto.tblPMLine AS line
    USING (SELECT LineId, LineName FROM moto.tblPMLine) AS existsLine
    ON line.LineId = existsLine.LineId
    WHEN MATCHED AND @DeleteMe = 1 THEN DELETE
    WHEN MATCHED AND @DeleteMe = 0 THEN UPDATE SET line.LineName = @LineName
    WHEN NOT MATCHED THEN INSERT(LineName) VALUES(@LineName);
    END
    GO

我知道这是一个非常简单的过程,但由于某种原因,当我使用以下命令时,它似乎没有生成任何条目。

    execute moto.procPM_UpdateLines null, 'First test', 0

有没有办法让我知道它遵循哪些选项(如果有的话)?


以前的存储过程已修复。

   MERGE INTO moto.tblPMLine AS T
   USING (SELECT @LineId as LineId, @LineName as LineName) AS S
   ON T.LineId = S.LineId
   WHEN MATCHED AND @DeleteMe = 0 THEN --UPDATE
        UPDATE SET LineName = @LineName 
   WHEN MATCHED AND @DeleteMe = 1 THEN --DELETE
        DELETE
   WHEN NOT MATCHED THEN--INSERT
        INSERT (LineName) VALUES (@LineName)    
   OUTPUT $action AS ChangesMade;

现在它插入、更新和删除,以及返回输出。

4

2 回答 2

12

您可以结合MERGEOUTPUT子句来获得某种“活动报告”(或调试“打印语句”)MERGE正在做什么 - 也许这会帮助您了解出了什么问题。

请参阅 Adam Machanic 的优秀博文 Dr. OUTPUT 或:我如何学会停止担心并喜欢 MERGE,它展示了该技术以及如何使用它

基本上它归结为使用OUTPUT带有语句的子句MERGE来获取正在发生的事情的信息 - 大致类似于:

MERGE INTO ......
WHEN MATCHED THEN
    .......
WHEN NOT MATCHED THEN
    ......
WHEN NOT MATCHED BY SOURCE THEN
    ........
OUTPUT
    $action AS dml_action,
    inserted.x AS new_x,
    deleted.x AS old_x,
    inserted.y AS new_y,
    deleted.y AS old_y;
于 2013-02-15T15:56:19.367 回答
1
MERGE moto.tblPMLine AS line
USING (SELECT LineId, LineName FROM moto.tblPMLine WHERE LineID = @LineID) AS existsLine

原谅我没用过MERGE。但是,我没有看到使用@LineID变量的代码。

于 2013-02-15T15:53:13.310 回答