How to get the value of autoincrement of last row at the insert

时间秒杀一切 提交于 2019-11-28 08:16:32

Use SCOPE_IDENTITY:

-- do insert

SELECT SCOPE_IDENTITY();

Which will give you:

The last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

Eddy Jawed

Just ran the code:

INSERT INTO Persons (FirstName) VALUES ('Joe');
SELECT ID AS LastID FROM Persons WHERE ID = @@Identity;

and it also works!

user1810132

What about this for last auto increment value

SELECT IDENT_CURRENT('tableName')-IDENT_INCR('tableName');

If you are using MySQL you get the auto increment ID of the last insert with:

SELECT LAST_INSERT_ID();

See here for full reference.

In my case I had to use @@Identity, because I was inserting into a view. It seems that SCOPE_IDENTITY only works for ones you have explicitly created.

See here:

http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!