加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 使用带有Scope_IDENTITY的MERGE INTO

发布时间:2020-12-12 06:31:35 所属栏目:MsSql教程 来源:网络整理
导读:当Merge into使用以下语句执行插入时,Scope_Identity返回正确的代理键信息.但是,当执行更新时,Scope_Identity和@@ Identity都会返回下一个可用的代理键.当我添加输出时,我在update和insert上都得到null. 如何在更新和插入上返回代理键? DECLARE @Surrogate_K
当Merge into使用以下语句执行插入时,Scope_Identity返回正确的代理键信息.但是,当执行更新时,Scope_Identity和@@ Identity都会返回下一个可用的代理键.当我添加输出时,我在update和insert上都得到null.

如何在更新和插入上返回代理键?

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
       )

output CurrentSet.*,@Surrogate_KEY ;

 print @Surrogate_KEY
 print @@IDENTITY
 print SCOPE_IDENTITY()

解决方法

使用 OUTPUT clause中的inserted伪表:
DECLARE @Surrogate_KEY bigint


MERGE INTO [dbo].[MyTable] ChangeSet
USING (SELECT   @NaturalKey1 AS NaturalKey1,blah
       )

output inserted.* ;

这将返回语句末尾表中的值(对于受影响的行).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读