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"
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.
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.
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.
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) .
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With