I'm trying to figure out how to query SQL Server if there is a lock with give name, aka is there a lock.
Is this correct, as it seems overly complicated?
Running
begin tran
print 'APPLOCK_TEST=' + convert(varchar(max), APPLOCK_TEST('public', 'testlock', 'Exclusive', 'Session'))
print 'APPLOCK_MODE=' + APPLOCK_MODE('public', 'testlock', 'Session')
declare @lock int
exec @lock = sp_getapplock @Resource = 'testlock', @Lockmode = 'Exclusive', @LockOwner = 'Session'
print(@lock)
print 'APPLOCK_TEST=' + convert(varchar(max), APPLOCK_TEST('public', 'testlock', 'Exclusive', 'Session'))
print 'APPLOCK_MODE=' + APPLOCK_MODE('public', 'testlock', 'Session')
returns
APPLOCK_TEST=1
APPLOCK_MODE=NoLock
0
APPLOCK_TEST=1
APPLOCK_MODE=Exclusive
Running this in another tab:
begin tran
print 'APPLOCK_TEST=' + convert(varchar(max), APPLOCK_TEST('public', 'testlock', 'Exclusive', 'Session'))
print 'APPLOCK_MODE=' + APPLOCK_MODE('public', 'testlock', 'Session')
returns
APPLOCK_TEST=0
APPLOCK_MODE=NoLock
So is the way to check if a lock is held?
Looks like a weird way to do such a check.
//APPLOCK_TEST remains 1 when the session is the session who has the lock
//otherwise this is 0
//APPLOCK_MODE is "NoLock" when a different session has the lock
//otherwise if its the same then APPLOCK_MODE = "Exclusive"
if(APPLOCK_TEST == 0 or APPLOCK_MODE != 'NoLock')
{
//there currently is a lock
}
else
{
//there is no lock.
}
I have been looking at
https://www.mssqltips.com/sqlservertip/3202/prevent-multiple-users-from-running-the-same-sql-server-stored-procedure-at-the-same-time/ https://github.com/madelson/DistributedLock/blob/5bd69af3f151710825f43ea1379a619a1b63ca1a/DistributedLock.SqlServer/SqlApplicationLock.cs#L164 https://www.endyourif.com/preventing-race-conditions-with-sp_getapplock/
and more..
Please assist with what SQL Server would be for checking if there currently is a lock, regardless of the connection used.