Using output to set a variable in a merge statement

后端 未结 1 1180
孤独总比滥情好
孤独总比滥情好 2021-02-19 22:24

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 22:45

    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_clause>::=

    SET
    ...
    @variable=expression

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