Created
October 14, 2021 12:59
-
-
Save lawrence-laz/80b7c12f0ba00dccd3e0d6714d52147a to your computer and use it in GitHub Desktop.
Query and kill sessions with locks in SQL server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @DatabaseName NVARCHAR(MAX) = 'your_database_name' | |
SELECT DISTINCT('KILL ' + CONVERT(varchar(10), request_session_id)) | |
FROM sys.dm_tran_locks | |
WHERE resource_database_id = DB_ID(@DatabaseName) | |
-- Adapted from https://blog.sqlauthority.com/2016/05/25/sql-server-fix-error-1807-not-obtain-exclusive-lock-database-model-retry-operation-later-part-2/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @DatabaseName NVARCHAR(MAX) = 'your_database_name' | |
IF EXISTS ( | |
SELECT * | |
FROM sys.dm_tran_locks | |
WHERE resource_database_id = DB_ID(@DatabaseName) | |
) | |
BEGIN | |
PRINT 'Database "' + @DatabaseName + '" in use!' | |
SELECT * | |
FROM sys.dm_exec_sessions s | |
INNER JOIN sys.dm_tran_locks l ON s.session_id = l.request_session_id | |
WHERE l.resource_database_id = DB_ID(@DatabaseName) | |
END | |
ELSE | |
PRINT 'Database "' + @DatabaseName + '" not in use.' | |
-- Adapted from https://blog.sqlauthority.com/2016/05/25/sql-server-fix-error-1807-not-obtain-exclusive-lock-database-model-retry-operation-later-part-2/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment