从最后插入的行中选择id。

4

我正在使用SQL Server Management Studio。我有一个名为faculty的表,其属性为idNamedean。我想在这个表中获取最后插入的记录id。

例如:

id  Name  dean
1   abc   xyz
2   efg   sss
3   ert   yui

我只想获取第三个id,而不是第三行。 在这种情况下,只需获取最后插入的id为3即可。

select max(id) as last_id from faculty - juergen d
2个回答

8

您可以在存储过程中使用 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. 

还有其他选项,例如

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

2. SELECT max(id) FROM table

请参考MSDN http://msdn.microsoft.com/zh-cn/library/ms190315.aspx以及http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/


1
@@IDENTITY 将返回任何表中任何会话中最后生成的标识值,IDENT_CURRENT('TableName') 将返回任何会话中 TableName 的最后生成的标识值,最后 SCOPE_IDENTITY() 将返回当前会话中最后生成的标识值。最安全的选择是 SCOPE_IDENTITY(),但如果您正在处理多个插入,则 OUTPUT 子句是您的好朋友。 - M.Ali

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接