APPLOCK_TEST (Transact-SQL)
SQL Server 2008
Returns information about whether or not a lock can be granted on a particular application resource for a specified lock owner without acquiring the lock. APPLOCK_TEST is an application lock function, and it operates on the current database. The scope of application locks is the database.
In the following example, two users (User A and User B) with separate sessions run the following sequence of Transact-SQL statements.
User A runs:
USE AdventureWorks;
GO
BEGIN TRAN;
DECLARE @result int;
EXEC @result=sp_getapplock
@DbPrincipal='public',
@Resource='Form1',
@LockMode='Shared',
@LockOwner='Transaction';
SELECT APPLOCK_MODE('public', 'Form1', 'Transaction');
GO
User B then runs:
Use AdventureWorks;
GO
BEGIN TRAN;
SELECT APPLOCK_MODE('public', 'Form1', 'Transaction');
--Result set: NoLock
SELECT APPLOCK_TEST('public', 'Form1', 'Shared', 'Transaction');
--Result set: 1 (Lock is grantable.)
SELECT APPLOCK_TEST('public', 'Form1', 'Exclusive', 'Transaction');
--Result set: 0 (Lock is not grantable.)
GO
User A then runs:
EXEC sp_releaseapplock @Resource='Form1', @DbPrincipal='public'; GO
User B then runs:
SELECT APPLOCK_TEST('public', 'Form1', 'Exclusive', 'Transaction');
--Result set: '1' (The lock is grantable.)
GO
User A and User B then both run:
COMMIT TRAN; GO

