vba 为什么 SELECT SCOPE_IDENTITY() 返回 null?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3526800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:00:58  来源:igfitidea点击:

why does SELECT SCOPE_IDENTITY() return null?

sqlsql-servervba

提问by l--''''''---------''''''''''''

in what case does SELECT SCOPE_IDENTITY()return null?

在什么情况下SELECT SCOPE_IDENTITY()返回null?

i am doing this:

我正在这样做:

Set rs = cn.Execute("SELECT SCOPE_IDENTITY()", , adCmdText)
capture_id = rs.Fields(0)

and i getting capture_id=null

我得到 capture_id=null

回答by Pam Lahoud

To be more specific, SCOPE_IDENTITY() only returns the latest identity value generated within the same scope as the SCOPE_IDENTITY() call. In the example you posted, the SCOPE_IDENTITY() call is the only statement in the batch (hence the only statement within the current scope) so it will return null. If you want to get the latest identity value generated for a particular table, try IDENT_CURRENT('tablename'). This is not subject to scope, it just gives you the latest identity value generated for the given table.

更具体地说,SCOPE_IDENTITY() 仅返回在与 SCOPE_IDENTITY() 调用相同的范围内生成的最新标识值。在您发布的示例中,SCOPE_IDENTITY() 调用是批处理中唯一的语句(因此是当前范围内的唯一语句),因此它将返回 null。如果要获取为特定表生成的最新标识值,请尝试 IDENT_CURRENT('tablename')。这不受范围的限制,它只是为您提供为给定表生成的最新标识值。

回答by Ben.Vineyard

According to MSDN, "The SCOPE_IDENTITY() function will return the null value if the function is invoked before any INSERT statements into an identity column occur in the scope."

根据MSDN 的说法,“如果在作用域中出现对标识列的任何 INSERT 语句之前调用该函数,则 SCOPE_IDENTITY() 函数将返回空值。”