I am new to web application programming and handling concurrency using an RDBMS like SQL Server. I am using SQL Server 2005 Express Edition.
I am generating employee code in which the last four digits come from this query:
SELECT max(ID) FROM employees WHERE district = "XYZ";
I am not following how to handle issues that might arise due to concurrent connections. Many users can pick same max(ID) and while one user clicks “Save Record”, the ID might have already been occupied by another user.
How to handle this issue?
Here are two ways of doing what you want. The fact that you might end up with unique constraint violation on
EmpCodeI will leave you to worry about :).1. Use
scope_identity()to get the last inserted ID and use that to calculateEmpCode.Table definition:
Add one row to Employees. Should be done in a transaction to be sure that you will not be left with the default random value from
left(newid(), 10)inEmpCode:2. Make
EmpCodea computed column.Table definition:
Add one row to Employees: