如何得到自增id值

如何得到自增id值
如何得到SqlServer的自增ID:

SqlServer中的自增的ID的最后的值:

SELECT SCOPE_IDENTITY() --返回插入到同一作用域中的 IDENTITY 列内的最后一个 IDENTITY 值。
SELECT @@IDENTITY   --返回插入到当前会话中任何作用域内的最后一个 IDENTITY 列值
SELECT IDENT_CURRENT('TbName')--不受作用域和会话的限制,而受限于指定的表。IDENT_CURRENT 返回为任何会话和作用域中的特定表所生成的值。

一个作用域就是一个模块——存储过程、触发器、函数或批处理。因此,如果两个语句处于同一个存储过程、函数或批处理中,则它们位于相同的作用域中。


参考的例子如下:

USE pubs
DROP TABLE t6
DROP TABLE t7

GO
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
   SELECT @@IDENTITY as [@@IDENTITY]
   SELECT SCOPE_IDENTITY() as [SCOPE_IDENTITY]
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, which was inserted by the trigger.*/

SELECT SCOPE_IDENTITY()  
/* Returns the value 1, which was inserted by the
INSERT stmt 2 statements before this query.*/

return
SELECT IDENT_CURRENT('t7')
/* Returns value inserted into t7, i.e. in the trigger.*/

SELECT IDENT_CURRENT('t6')
/* Returns value inserted into t6, which was the INSERT statement 4 stmts before this query.*/

-- Do the following in Session 2
SELECT @@IDENTITY
/* Returns NULL since there has been no INSERT action
so far in this session.*/

SELECT SCOPE_IDENTITY()
/* Returns NULL since there has been no INSERT action
so far in this scope in this session.*/

SELECT IDENT_CURRENT('t7')
/* Returns the last value inserted into t7.*/


总结:
对于马上使用的刚才插入的新记录ID用SCOPE_IDENTITY()是最合适的;
对于想要得到一系列的操作中最后得到的那个自增的ID最好用@@IDENTITY;
对于想要得到一个表中的最后一个插入操作所产生的ID的最好用IDENT_CURRENT('TBName')


出处:http://blog.csdn.net/greatplain/archive/2004/11/15/181948.aspx

原文地址:https://www.cnblogs.com/no7dw/p/1530727.html