• SP_getapplock needs to be run inside a transaction.

    I'm not convinced that this would be the best idea but...

    In order for you to make this work for your situation, you would need to maintain a connection to the database and leave a transaction uncommitted while the user is editing that record. When the users is finished editing/viewing, the transaction is committed. This 'hanging' transaction should ONLY have the call to sp_getapplock (exclusive mode)!

    When the transaction is committed, the lock is released and other clients can then acquire the lock. If the connection is broken, the lock is released (this is because SQL server will rollback open transactions when a connection is lost)

    Many people (myself included) will tell you that it is generally a bad idea to leave a transaction open like that, the main reason is it can cause blocking. If all you are doing is EXECing sp_getapplock, blocking won't really be an issue. It also eats up resources, holding connections open indefinitely. These are things you would need to consider. I'm sure others will add to this list of things to consider/reasons not to do this.

    On the upside, you could use APPLOCK_TEST to check for a lock in your form constructor and if the user crashed out, the lock would be released (although it depends where the crash was, in the application or the citrix/terminal services client).

    An alternative would be to write a SessionLockID and a datestamp. That way you could time out locks after a set period of time.

    SQL guy and Houston Magician