Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the next identity value from SQL Server

I need to get the next identity value from SQL Server.

I use this code :

SELECT IDENT_CURRENT('table_name') + 1 

This is correct, but when the table_name is empty (and next identity value is "1") returned "2" but result is "1"

like image 550
Mehdi Esmaeili Avatar asked Dec 27 '13 17:12

Mehdi Esmaeili


People also ask

How do I find the next identity value in SQL Server?

You cannot reliably find out the next identity value - until you've actually inserted a new row into the table. Stop trying - you won't succeed - just accept the fact you cannot know the identity value before the row is actually inserted into the table and SQL Server has assigned the value.

How do I select next id in SQL?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.

How can I get identity value after inserting SQL Server?

Once we insert a row in a table, the @@IDENTITY function column gives the IDENTITY value generated by the statement. If we run any query that did not generate IDENTITY values, we get NULL value in the output. The SQL @@IDENTITY runs under the scope of the current session.

How can get auto increment value in SQL Server?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .


2 Answers

I think you'll want to look for an alternative way to calculate the next available value (such as setting the column to auto-increment).

From the IDENT_CURRENT documentation, regarding empty tables:

When the IDENT_CURRENT value is NULL (because the table has never contained rows or has been truncated), the IDENT_CURRENT function returns the seed value.

It doesn't even seem all that reliable, especially if you end up designing an app that has more than one person writing to the table at the same time.

Be cautious about using IDENT_CURRENT to predict the next generated identity value. The actual generated value may be different from IDENT_CURRENT plus IDENT_INCR because of insertions performed by other sessions.

like image 156
Grant Winney Avatar answered Oct 13 '22 00:10

Grant Winney


In case when your table will be empty then this query will work perfectly.

SELECT   CASE     WHEN (SELECT         COUNT(1)       FROM tablename) = 0 THEN 1     ELSE IDENT_CURRENT('tablename') + 1   END AS Current_Identity; 
like image 43
Abhijit Gosavi Avatar answered Oct 12 '22 22:10

Abhijit Gosavi