从最后插入的行中选择 id

use*_*881 2 sql t-sql sql-server sql-server-2008

我正在使用 SQL Server Management Studio。我有一个名为 Faculty 的表,它的属性是id,Namedean。我想在此表中获取最后插入的记录 ID。

例如:

id  Name  dean
1   abc   xyz
2   efg   sss
3   ert   yui
Run Code Online (Sandbox Code Playgroud)

我只想获得第 3 个 ID,而不是第 3 行。在这种情况下,最后插入的 id 为 3。

Hav*_*ame 5

您可以SCOPE_IDENTITY()在存储过程中使用 来获取最后插入的记录 ID。

SELECT SCOPE_IDENTITY() :- It will returns the last identity value inserted into an 
identity column in the same scope.

SELECT @@IDENTITY :- @@IDENTITY will return the last identity value entered 
into a table in your current session. 

SELECT IDENT_CURRENT(‘tablename’) :- IDENT_CURRENT is not limited by scope and
session; it is limited to a specified table. 
Run Code Online (Sandbox Code Playgroud)

还有其他选择,例如

1. Select Top 1 id From Table Order by id desc

2. SELECT max(id) FROM table
Run Code Online (Sandbox Code Playgroud)

请参阅 msdn http://msdn.microsoft.com/en-us/library/ms190315.aspxhttp://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs- ident_current-retrieve-last-inserted-identity-of-record/