sp_GetAppLock SQL Server 2019 中没有交易

sp_GetAppLock without transaction in SQL Server 2019

i运行var 的答案 here 中的代码在 SQL Server 2019 中不再有效。当我 运行 此代码(且仅此代码)

EXEC sp_getapplock @Resource = 'Lock ID', @LockOwner = 'Session', @LockMode = 'Exclusive';
print 'omg' 
EXEC sp_releaseapplock @Resource = 'Lock ID';

我明白了

The statement or function must be executed in the context of a user transaction.

这些天我是如何在没有交易的情况下获得应用锁的?

为了匹配锁定和释放,您必须为两个操作指定相同的@LockOwner

declare @Status as Int;
EXEC @Status = sp_getapplock @Resource = 'Lock ID', @LockOwner = 'Session', @LockMode = 'Exclusive';
print @Status;
print 'omg';
EXEC @Status = sp_releaseapplock @Resource = 'Lock ID', @LockOwner = 'Session';
print @Status;