将 MERGE INTO 与 Scope_IDENTITY 结合使用
当 Merge into
使用以下语句执行 insert
时,Scope_Identity
返回正确的代理键信息。但是,当执行更新
时,Scope_Identity
和@@Identity
都会返回下一个可用代理键。当我添加 output
时,我在 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, blah
)
output CurrentSet.*, @Surrogate_KEY ;
print @Surrogate_KEY
print @@IDENTITY
print SCOPE_IDENTITY()
When Merge into
does an insert
with the following statement, Scope_Identity
returns the correct surrogate key information. However when an update
is performed both Scope_Identity
and @@Identity
return the next available surrogate key. And when I added the output
, I get a null on both update
and insert
.
How do I return the surrogate key on both the update
and the insert
?
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 OUTPUT 子句中使用
插入
伪表:这会返回任何内容这些值位于语句末尾的表(针对受影响的行)中。
Use the
inserted
pseudo table in your OUTPUT clause:This returns whatever the values are in the table (for the affected rows) at the end of the statement.