65.9K
CodeProject 正在变化。 阅读更多。
Home

@@IDENTITY、SCOPE_IDENTITY、IDENT_CURRENT 的区别

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.64/5 (42投票s)

2010年8月22日

CPOL

1分钟阅读

viewsIcon

285339

downloadIcon

697

SQL @@IDENTITY、SCOPE_IDENTITY、IDENT_CURRENT 函数的区别

引言

在大多数应用场景中,我们需要通过 SQL 查询获取最新插入的行信息。为此,我们有多种选择,例如:

  • @@IDENTITY
  • SCOPE_IDENTITY
  • IDENT_CURRENT

这三个函数都返回最近生成的标识值。但是,在这些函数中定义“最近”的范围和会话有所不同。

Compare

@@IDENTITY

它返回当前会话中任何表的最后一个生成的标识值,跨所有作用域。

让我解释一下... 假设我们在表上创建了一个 insert 触发器,该触发器在另一个具有生成标识列的表中插入一行,那么 @@IDENTITY 将返回由触发器创建的标识记录。

SCOPE_IDENTITY

它返回当前会话和当前作用域中任何表的最后一个生成的标识值。

让我解释一下... 假设我们在表上创建了一个插入触发器,该触发器在另一个具有生成标识列的表中插入一行,那么 SCOPE_IDENTITY 的结果不受影响,但如果触发器或用户定义的函数影响了生成该值的同一表,则返回该标识记录,那么 SCOPE_IDENTITY 将返回由触发器或用户定义的函数创建的标识记录。

IDENT_CURRENT

它返回在任何会话和任何作用域中特定表的最后一个生成的标识值。

换句话说,我们可以说它不受作用域和会话的影响,它仅依赖于特定表,并返回在任何会话或作用域中生成的与该表相关的标识值。

SQL 查询

我将通过一些示例查询来解释上述过程,希望有所帮助

CREATE TABLE Parent(id int IDENTITY);

CREATE TABLE Child(id int IDENTITY(100,1));

GO

CREATE TRIGGER Parentins ON Parent FOR INSERT

AS

BEGIN

   INSERT Child DEFAULT VALUES

END;

GO

--End of trigger definition

SELECT id FROM Parent;
--id is empty.

SELECT id FROM Child;
--ID is empty. 

--Do the following in Session 1
INSERT Parent DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/

SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the
INSERT statement two statements before this query.*/ 

SELECT IDENT_CURRENT('Child');

/* Returns value inserted into Child, that is in the trigger.*/

SELECT IDENT_CURRENT('Parent');

/* Returns value inserted into Parent. 
This was the INSERT statement four statements before this query.*/ 

-- Do the following in Session 2.

SELECT @@IDENTITY;

/* Returns NULL because there has been no INSERT action
up to this point in this session.*/ 

SELECT SCOPE_IDENTITY();

/* Returns NULL because there has been no INSERT action
up to this point in this scope in this session.*/

SELECT IDENT_CURRENT('Child');

/* Returns the last value inserted into Child.*/

历史

  • 2010年8月22日:初始发布
© . All rights reserved.