Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Which is the right way to set identity column?

Way 1:

Auto-generated identity
SQL
identity(1,1)


Way 2:

Manual generated Identity
SQL
select @Identity = max(isnull(pkColumn,0))+1 from table


Please clarify..
Regards,
SJ
Posted

First way is right way, because it guarantee data integrity!
Read this: IDENTITY()[^] to get explanation ;)

Second way is pseudo-identity and does NOT guarantee unical numbers and data integrity. Why?
Imagine this situation: Your MAX(PK)=500. You have added 1 record, so your "identity" is equal: MAX+1=501. Delete last record and add it again. What number ("identity") you'll get? What happend if in other table exists foreign key with 501? You'll lose data integrity.
 
Share this answer
 
v2
Comments
codeninja-C# 7-Jun-13 13:07pm    
Thanks, good explanation +5
Maciej Los 7-Jun-13 13:57pm    
Thank you and you're welcome ;)
Way 1:
[Id] [int] IDENTITY(1,1) NOT NULL
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900