sql-server – 当@@ IDENTITY没有时,SCOPE_IDENTITY如何返回null?

前端之家收集整理的这篇文章主要介绍了sql-server – 当@@ IDENTITY没有时,SCOPE_IDENTITY如何返回null?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
执行插入后,我选择SCOPE_IDENTITY或@@ IDENTITY.

SCOPE_IDENTITY返回null,但@@ IDENTITY不返回.

我不明白这是怎么可能的.

你能想到这样的原因吗?

解决方法

以下是SCOPE_IDENTITY()将为null但@@ IDENTITY将具有值的示例:

insert into a table with no identity,
that table has an insert trigger that
then inserts into a history table with
an identity. SCOPE_IDENTITY() will be
null (no identity in the local scope),
but @@IDENTITY will report the
identity from the trigger.

FYI,有一个已知的错误SCOPE_IDENTITY():https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=328811

您最好的使用身份验证是使用OUTPUT INTO,它可以捕获一组ID,并且不受SCOPE_IDENTITY()错误的限制:

declare @x table (tableID int identity not null primary key,datavalue varchar(10))
declare @y table (tableID int,datavalue varchar(10))

INSERT INTO @x values ('aaaa')
INSERT INTO @x values ('bbbb')
INSERT INTO @x values ('cccc')
INSERT INTO @x values ('dddd')
INSERT INTO @x values ('eeee')


INSERT INTO @x
    (datavalue)
    OUTPUT INSERTED.tableID,INSERTED.datavalue     --<<<<OUTPUT INTO Syntax
    INTO @y                                         --<<<<OUTPUT INTO Syntax
SELECT
    'value='+CONVERT(varchar(5),dt.NewValue)
    FROM (SELECT id as NewValue from sysobjects where id<20) dt
    ORDER BY dt.NewValue


select * from @x
select * from @y
原文链接:https://www.f2er.com/mssql/82212.html

猜你在找的MsSQL相关文章