Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
gustaf111
Starting Member
1 Post |
Posted - 2011-09-20 : 13:15:03
|
| Hello, I have two problems that are connected that I would like to solve. I hope anybody that knew this have time to help me!1) I have an application that requests a new ID from my MS SQL Server Express 2088. I would like the application to get next avaiable ID. e.g if the ID's are 1,2,3,5 then I would like the application to get ID = 4 and if the list lock like: 1,2,3,4 then I would like the application to get ID = 5.2) How do I prevent two application to get the same ID from the SQL server ?Cheers Gustaf |
|
|
ehorn
Master Smack Fu Yak Hacker
1632 Posts |
Posted - 2011-09-20 : 16:29:20
|
Hello,Here are some ideas for your problems;1) One option would be to create a table of numbers and then compare it against you id's to find the min id missing in the sequence. Something like; create table #numbers (n int primary key)insert #numbers (n) select 1 union all select 2 union allselect 3 union all select 4 union allselect 5 union all select 6 union allselect 7 union all select 8--... to as large as requiredcreate table #t (id int primary key)insert #t(id)select 1 union allselect 2 union allselect 3 union allselect 5 --the next idselect MIN(n) AS idfrom #numbers nleft join #t t on t.id = n.nwhere t.id is null--clean up exampledrop table #numbers, #t 2) One option might be to wrap the retrieval of the ID in a transaction and place a reserved flag on the numbers table, then commit this transaction and return the result to the user. If the id is not used, update the reserved flag. The checks would occur at appropriate places within the application.HTH. |
 |
|
|
|
|
|