gpt4 book ai didi

sql - 将 MERGE INTO 与 Scope_IDENTITY 结合使用

转载 作者:行者123 更新时间:2023-12-02 23:27:58 25 4
gpt4 key购买 nike

Merge into 使用以下语句执行insert 时,Scope_Identity 返回正确的代理键信息。但是,当执行更新时,Scope_Identity@@Identity 都会返回下一个可用代理键。当我添加 output 时,我在 updateinsert 上都得到了 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, 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,
@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.* ;

这将返回语句末尾表中(受影响的行)的任何值。

关于sql - 将 MERGE INTO 与 Scope_IDENTITY 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6152786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com