Skip to content

Commit 1609ec3

Browse files
committed
remove TOP from main deadlock_data query, but still respect @top if needed
1 parent 5e4e928 commit 1609ec3

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

sp_BlitzLock.sql

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ You need to use an Azure storage account, and the path has to look like this: ht
187187
finding NVARCHAR(4000)
188188
);
189189

190-
DECLARE @d VARCHAR(40), @StringToExecute NVARCHAR(4000),@StringToExecuteParams NVARCHAR(500),@r NVARCHAR(200),@OutputTableFindings NVARCHAR(100);
190+
DECLARE @d VARCHAR(40), @StringToExecute NVARCHAR(4000),@StringToExecuteParams NVARCHAR(500),@r NVARCHAR(200),@OutputTableFindings NVARCHAR(100),@DeadlockCount INT;
191191
DECLARE @ServerName NVARCHAR(256)
192192
DECLARE @OutputDatabaseCheck BIT;
193193
SET @d = CONVERT(VARCHAR(40), GETDATE(), 109);
@@ -309,7 +309,7 @@ You need to use an Azure storage account, and the path has to look like this: ht
309309
WITH xml
310310
AS ( SELECT CONVERT(XML, event_data) AS deadlock_xml
311311
FROM sys.fn_xe_file_target_read_file(@EventSessionPath, NULL, NULL, NULL) )
312-
SELECT TOP ( @Top ) ISNULL(xml.deadlock_xml, '') AS deadlock_xml
312+
SELECT ISNULL(xml.deadlock_xml, '') AS deadlock_xml
313313
INTO #deadlock_data
314314
FROM xml
315315
LEFT JOIN #t AS t
@@ -322,6 +322,17 @@ You need to use an Azure storage account, and the path has to look like this: ht
322322
ORDER BY xml.deadlock_xml.value('(/event/@timestamp)[1]', 'datetime') DESC
323323
OPTION ( RECOMPILE );
324324

325+
/*Optimization: if we got back more rows than @Top, remove them. This seems to be better than using @Top in the query above as that results in excessive memory grant*/
326+
SET @DeadlockCount = @@ROWCOUNT
327+
IF( @Top < @DeadlockCount ) BEGIN
328+
WITH T
329+
AS (
330+
SELECT TOP ( @DeadlockCount - @Top) *
331+
FROM #deadlock_data
332+
ORDER BY #deadlock_data.deadlock_xml.value('(/event/@timestamp)[1]', 'datetime') ASC)
333+
DELETE FROM T
334+
END
335+
325336
/*Parse process and input buffer XML*/
326337
SET @d = CONVERT(VARCHAR(40), GETDATE(), 109);
327338
RAISERROR('Parse process and input buffer XML %s', 0, 1, @d) WITH NOWAIT;

0 commit comments

Comments
 (0)