Using output to set a variable in a merge statement

后端 未结 1 1730
北恋
北恋 2021-02-19 22:32

I have a merge statement that should update or insert a single record always. I want to remember the ID of that statement in a variable. It looks like this:

DECL         


        
1条回答
  •  忘了有多久
    2021-02-19 23:06

    No, you have to use a table variable with OUTPUT

    However, you can do this...

    ...
    WHEN MATCHED THEN 
        UPDATE
        SET
           @int = ID,
           somecolumn = 'something'
    WHEN NOT MATCHED THEN
        INSERT 
        VALUES ('stringtomatch',
            'something');
    
    SET @int = ISNULL(@int, SCOPE_IDENTITY());
    

    The "assign in UPDATE" has been a valid syntax for SQL Server for a long time. See MERGE on MSDN too. Both say this:

    ...
    ::=

    SET
    ...
    @variable=expression

    0 讨论(0)
提交回复
热议问题