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

I have a table student and have a column ID (int ) , now i want to insert rows by adding ID+1 in table.

I got max id by MAX(ID)+1 when i insert one row and so on.Issue happen when multiple user get the same ID when they execute same query at same time and insert the same ID to table.
Posted

1 solution

To prevent this situation you should set INDEITY=true for your column and get the value by using SCOPE_IDENTITY() after insertion of record. This way you can prevent duplicate value insertion.
 
Share this answer
 
Comments
Shrikant_Yadav 9-Oct-15 7:52am    
what would happen if column type is nvarchar? With nvarchar column i have vlaue "ABC001" and I am getting max value like MAX(RIGHT(ID,3)) +1 will be 002 and same would happen to other users ?
Anupam Shukla 2009 9-Oct-15 8:45am    
First of all as per database normalization recommendation you should not create a column with multi valued dependency (string + max(Id)). You can create a view to use column with combination or store the string part in separate table (depends upon situation).

But if it is compulsory to store values in such way (string + max(Id)) you can use TRANSACTION with TRANSACTION ISOLATION LEVEL = READ COMMITTED. This way you can prevent to read old ID value while other write operation is in progress and you will always get final (committed) value.

Please explain your scenario so I can understand the issue exactly.

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