获得SQL自增列(IDENTITY)的值的方法记载

SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY 是相似的函数,因为它们都返回插入到标识列中的值。

SCOPE_IDENTITY 和 @@IDENTITY 返回在当前会话中的任何表内所生成的最后一个标识值。但是,

  1. SCOPE_IDENTITY 只返回插入到当前作用域中的值;
  2. @@IDENTITY 不受限于特定的作用域。

IDENT_CURRENT 不受作用域和会话的限制,而受限于指定的表。IDENT_CURRENT 返回为任何会话和作用域中的特定表所生成的值。

  1. IDENT_CURRENT 返回为某个会话和用域中的指定表生成的最新标识值。
  2. @@IDENTITY 返回为跨所有作用域的当前会话中的某个表生成的最新标识值。
  3. SCOPE_IDENTITY 返回为当前会话和当前作用域中的某个表生成的最新标识值。

测试代码:

CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT 
AS
BEGIN
   INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition

SELECT   * FROM t6;
--id is empty.

SELECT   * FROM t7;
--ID is empty.

--Do the following in Session 1
INSERT t6 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('t7');
/* Returns value inserted into t7, that is in the trigger.*/

SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. 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('t7');
/* Returns the last value inserted into t7.*/

如果想在当前的存储过程内获得当前插入表的主键,用SCOPE_IDENTITY还是比较合适吧。

摘录帮助文档

posted @ 2011-03-24 13:36  李传涛  阅读(2501)  评论(0编辑  收藏  举报