简体   繁体   English

将 MERGE INTO 与 Scope_IDENTITY 一起使用

[英]Using MERGE INTO with Scope_IDENTITY

When Merge into does an insert with the following statement, Scope_Identity returns the correct surrogate key information.Merge into使用以下语句进行insert时, Scope_Identity返回正确的代理键信息。 However when an update is performed both Scope_Identity and @@Identity return the next available surrogate key.但是,当执行update时, Scope_Identity@@Identity都会返回下一个可用的代理键。 And when I added the output , I get a null on both update and insert .当我添加output时,我在updateinsert上都得到了 null 。

How do I return the surrogate key on both the update and the insert ?如何在updateinsert上返回代理键?

DECLARE @Surrogate_KEY bigint


MERGE INTO [dbo].[MyTable] ChangeSet
USING (SELECT   @NaturalKey1 AS NaturalKey1, 
                @NaturalKey2 AS NaturalKey2, 
                @NaturalKey3 AS NaturalKey3,
                @Surrogate_KEY AS Surrogate_KEY) CurrentSet
ON  ChangeSet.NaturalKey1 = CurrentSet.NaturalKey1 AND 
    ChangeSet.NaturalKey2 = CurrentSet.NaturalKey2 AND 
    ChangeSet.NaturalKey3 = CurrentSet.NaturalKey3      
WHEN MATCHED THEN 
    UPDATE SET blah, blah, blah 

WHEN NOT MATCHED 
    THEN INSERT VALUES
       (
        blah, blah, blah
       )

output CurrentSet.*, @Surrogate_KEY ;

 print @Surrogate_KEY
 print @@IDENTITY
 print SCOPE_IDENTITY() 

Use the inserted pseudo table in your OUTPUT clause :OUTPUT 子句中使用inserted的伪表:

DECLARE @Surrogate_KEY bigint


MERGE INTO [dbo].[MyTable] ChangeSet
USING (SELECT   @NaturalKey1 AS NaturalKey1, 
                @NaturalKey2 AS NaturalKey2, 
                @NaturalKey3 AS NaturalKey3,
                @Surrogate_KEY AS Surrogate_KEY) CurrentSet
ON  ChangeSet.NaturalKey1 = CurrentSet.NaturalKey1 AND 
    ChangeSet.NaturalKey2 = CurrentSet.NaturalKey2 AND 
    ChangeSet.NaturalKey3 = CurrentSet.NaturalKey3      
WHEN MATCHED THEN 
    UPDATE SET blah, blah, blah 

WHEN NOT MATCHED 
    THEN INSERT VALUES
       (
        blah, blah, blah
       )

output inserted.* ;

This returns whatever the values are in the table (for the affected rows) at the end of the statement.这将返回语句末尾表中的任何值(对于受影响的行)。

DECLARE @Id ...
--
MERGE
    dbo.Table AS Tgt
USING
    (
        SELECT
            <Keys>
    ) AS Src
    ON Src.<Keys> = Tgt.<Keys>
WHEN MATCHED THEN
    UPDATE SET
        <...>
        ,@Id = Tgt.Id
WHEN NOT MATCHED THEN
    INSERT
    (
        ...
    )
    VALUES
    (
        ...
    )
;--
RETURN/SET/PRINT ISNULL(@Id, SCOPE_IDENTITY())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM