Programatically and Failsafe Lock Records in MSSQL 7
How would you like to be able to determine if a record has been locked in
MSSQL Server and not get that annoying 'Record has been changed by another User'
when you finally try to post your changes?
There is an easy approach (quite easy) but it has to be implemented
programatically.
This is how.
For every record you want to lock to this:
Create a global temporary table that is named after the table on which the record
is, together with the Unique Id of the table. For example, if you have a
table named customers, with a unique id field called Uid and you want to lock the
record with uid=14, create the table using this query:
Create table ##Customers14 (id int null)
When you want to unlock the record just drop that table:
Drop table ##Customers14
Now lets say that another user wants to use the same record. His client programm
tries to create the same global temporary table, but fails with an exception,
because no two global temporary tables can have the same name. Trap the exception
in a try-except clause and you are home free.
TIPS.
a)
Use this only for SQLServer 7 and above. SQL 6.5 and below have a terrible way
of handling Temprorary tables that gives a lot of overhead.
b)
You can create any kind of collumn in your temporary table, so you can have
info like what time the record was locked and by what user.
c)
Never use this approach if there is a chance someone will forget his computer
open on a record for hours, and that computer is located lets say 100 miles
from the server!!!
d)
If the connection is lost by lets say an application error, the table is
automatically droped by the SQL Server.
e)
If the computer shutsdown by a power failure, the SQL Server waits for about
15 minutes and then drops the temporary table, or if the computer logs on again
the table is droped automatically.
f)
If you don't want to have to handle an exception you can also check for the
existance of the Temporary table in the Master database