How to get the next value of the primary key as a identity

Sometime, I may delete the last recorder, but still want to get the next value
turbot_yuAsked:
Who is Participating?
 
AaronAbendConnect With a Mentor Commented:
What happens if you insert 10 values and someone deletes record 4? You still have a gap in the values. Using a DBCC command (some of which are regarded as back door operations for emergencies) to go back, use ID 4, and reset back to 10, would be timeconsuming and would have to lock the table to prevent a primary key violation.

Note that if you are doing a transaction, you can use


SELECT top 1 IDENT_CURRENT('e') from e1

to get the current maximum value and write code to avoid "wasting" an id.

And I still think it's a bad idea!  


0
 
AaronAbendConnect With a Mentor Commented:
there is no way to do this.  You really do not want to care what your primary key values are, which is why the "rules of relational database" include a rule that says that primary keys must not contain data. If you have questions about why let me know and I can tell you about systems I had to clean up because they violated this rule.

 
0
 
AaronAbendConnect With a Mentor Commented:
I was wrong - it can be done...

DBCC CHECKIDENT
(
        'e1'  ,   RESEED  , 1    
)
 resets the identity on table e1 to 1 (next value will be 2)

I still recommend against it
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
AaronAbendConnect With a Mentor Commented:
sorry - I did not clarify my SQL...


SELECT top 1 IDENT_CURRENT('identity_columnname') from tablename

0
 
turbot_yuAuthor Commented:
when trying SELECT top 1 IDENT_CURRENT ('identity_groupid') from [group], it give null
when trying select max(groupid) from [group], it gives 6
0
 
Guy Hengel [angelIII / a3]Connect With a Mentor Billing EngineerCommented:
as said already by AaronAbend: DON'T

you can use the DBCC CHECKIDENT(yourtable, RESEED)  to reset the identity to the last value (so your next insert will take the next value), but don't try to specify a explicit value in normal circumstances.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.