简体   繁体   中英

Get latest identity, such as ID, from an empty table SQL

I have noticed that SQL keeps track of the latest identity (field it automatically increments each time a new record is created). I want to retrieve the latest identity from the table using C#. Unfortunately most of the time the table is empty (records are written and removed after a while, so often the table is empty). Is this possible to do this within the bounds of the C# SQL API or do I have to create a stored procedure to retrieve this?

在此处输入图片说明

To better explain. If the row above was removed, the next ID number for the next record would be 32. I want to retrieve 32 before the record is written in, in the situation where the table is empty.

SELECT IDENT_CURRENT('table_name')+1;

IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.

http://msdn.microsoft.com/en-us/library/ms175098.aspx


However, although this shows what the next ID will be, this doesn't always mean it will be the next ID entered by yourself. Someone else could INSERT a new record before you.

In short, there is no way of returning the value of what you will next be inserting.

That would be the following query

DBCC CHECKIDENT ('[TableName]', NORESEED )

Just in case the increment is not the regular "1":

SELECT IDENT_CURRENT('mytable') + IDENT_INCR('mytable')

Of course, all these rely on the identity column having been populated consistently, ie no messing with manual inserts or reseeding. And Curt has mentioned the possible concurrency issue if you're going to use this ID for your insert directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM