forked from ktaranov/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbo.usp_who5.sql
1651 lines (1327 loc) · 56 KB
/
dbo.usp_who5.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
-----------------------------------------------------------------------------------------------------------------------------
-- Error Trapping: Check If Procedure Already Exists And Create Shell If Applicable
-----------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID (N'dbo.usp_who5', N'P') IS NULL
BEGIN
EXECUTE (N'CREATE PROCEDURE dbo.usp_who5 AS SELECT 1 AS shell')
END
GO
-----------------------------------------------------------------------------------------------------------------------------
-- Stored Procedure Details: Listing Of Standard Details Related To The Stored Procedure
-----------------------------------------------------------------------------------------------------------------------------
-- Purpose: Return Information Regarding Current Users / Sessions / Processes On A SQL Server Instance
-- Create Date (MM/DD/YYYY): 10/27/2009
-- Developer: Sean Smith (s.smith.sql AT gmail DOT com)
-- Latest Release: http://www.sqlservercentral.com/scripts/sp_who/68607/
-- Script Library: http://www.sqlservercentral.com/Authors/Scripts/Sean_Smith/776614/
-- LinkedIn Profile: https://www.linkedin.com/in/seanmsmith/
-----------------------------------------------------------------------------------------------------------------------------
-- Modification History: Listing Of All Modifications Since Original Implementation
-----------------------------------------------------------------------------------------------------------------------------
-- Description: Added "@Database_Name" Filter Variable
-- : Added "Last_Wait_Type", "Query_Plan", And "Wait_Type" Fields To Output
-- : Changed Code Formatting
-- : Converted Script To Dynamic-SQL
-- Date (MM/DD/YYYY): 08/08/2011
-- Description: Added "C" Type "@Filter" Option
-- : Added "Plan_Cache_Object_Type", "Plan_Object_Type", "Plan_Times_Used", And "Plan_Size_MB" Fields To Output
-- : Changed Help Output From RAISERROR To PRINT
-- : Merged "I?" And "O?" Help Parameters Into "?"
-- : Renamed Input Parameters
-- : Rewrote Time Calculation Logic
-- Date (MM/DD/YYYY): 11/09/2011
-- Description: Added "SQL_Statement_Current" And "End_Of_Batch" Fields To Output
-- : Added System Process Indicator To "SPID"
-- : Expanded "Running" Type Indicators
-- Date (MM/DD/YYYY): 02/01/2012
-- Description: Bug Fixes
-- : Changed Code Formatting
-- : Changed Date Calculation Method
-- Date (MM/DD/YYYY): 08/19/2013
-- Description: Added "Batch_Pct", "Command_Completion", "Command_Pct", "Command_Time_Left", "Deadlock_Priority", "Isolation_Level", "Last_Row_Count", "Lock_Details", "Lock_Timeout_Seconds", And "Previous_Error" Fields To Output
-- Date (MM/DD/YYYY): 11/24/2013
-- Description: Massive Rewrite Of Entire Stored Procedure
-- Date (MM/DD/YYYY): 11/28/2015
-- Description: Added "Log_Database_Count", "Log_Details", "Log_Records_All", "Log_Reserved_MB_All", "Log_Used_MB_All", "TempDB_Session_Current_MB", "TempDB_Session_Total_MB", "TempDB_Task_Current_MB", "TempDB_Task_Total_MB", "Threads", "Transaction_ID", "Transaction_State", "Transaction_Time", "Transaction_Type" Fields To Output
-- : Added Deadlock Detection To "Blocking" Output Field
-- : No Longer Displays Results At The Execution Context ID (ECID) Level
-- : Removed "@SQL_Text" Filter Variable
-- : Removed "Batch_Pct", "End_Of_Batch", "Plan_Cache_Object_Type", "Plan_Object_Type", "Plan_Size_MB", "Plan_Times_Used", "Previous_Error" Fields From Output
-- : Renamed "SPECID" To "SPID", "Open_Trans" To "Transactions" Output Fields
-- Date (MM/DD/YYYY): 05/07/2016
-- Description: Another Massive Rewrite Of Entire Stored Procedure To Improve Performance
-- Date (MM/DD/YYYY): 01/20/2018
-----------------------------------------------------------------------------------------------------------------------------
-- Main Query: Create Procedure
-----------------------------------------------------------------------------------------------------------------------------
ALTER PROCEDURE dbo.usp_who5
@Filter AS NVARCHAR (5) = NULL
,@Database_Name AS NVARCHAR (512) = NULL
,@Exclude_Lock AS BIT = 1
,@Exclude_Log AS BIT = 1
,@Exclude_Plan AS BIT = 1
,@Exclude_SQL AS BIT = 0
,@Exclude_SQL_XML AS BIT = 1
,@Exclude_TXN AS BIT = 1
,@Login AS NVARCHAR (128) = NULL
,@SPID AS SMALLINT = NULL
AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
SET ARITHABORT OFF
SET ARITHIGNORE ON
SET TEXTSIZE 2147483647
-----------------------------------------------------------------------------------------------------------------------------
-- Declarations / Sets: Declare And Set Variables
-----------------------------------------------------------------------------------------------------------------------------
DECLARE
@Ampersand AS NVARCHAR (1)
,@CR_LF AS NCHAR (2)
,@CR_LF_Tab AS NCHAR (3)
,@Database_ID AS INT
,@Date_Now AS DATETIME
,@Filter_Active AS BIT
,@Filter_Blocked AS BIT
,@Filter_Sleeping AS BIT
,@Filter_System AS BIT
,@Plan_Handle AS VARBINARY (64)
,@Print AS NVARCHAR (MAX)
,@SQL_Handle AS VARBINARY (64)
,@SQL_String AS NVARCHAR (MAX)
SET @Ampersand = N'&'
SET @CR_LF = NCHAR (13) + NCHAR (10)
SET @CR_LF_Tab = @CR_LF + NCHAR (9)
SET @Database_Name = NULLIF (@Database_Name, N'')
SET @Date_Now = GETDATE ()
SET @Filter_Active = (CASE
WHEN @Filter LIKE N'%A%' THEN 1
ELSE 0
END)
SET @Filter_Blocked = (CASE
WHEN @Filter LIKE N'%B%' THEN 1
ELSE 0
END)
SET @Filter_Sleeping = (CASE
WHEN @Filter LIKE N'%S%' THEN 1
ELSE 0
END)
SET @Filter_System = (CASE
WHEN @Filter LIKE N'%X%' THEN 1
ELSE 0
END)
SET @Login = NULLIF (@Login, N'')
-----------------------------------------------------------------------------------------------------------------------------
-- Error Trapping: Check If "@Filter" Parameter Is An Input / Output Help Request
-----------------------------------------------------------------------------------------------------------------------------
IF @Filter = N'?'
BEGIN
SET @Print =
N'
Optional input parameters:
@Filter : Limit the result set by passing one or more values listed below (can be combined in any order)
A - Active sessions only (includes sleeping SPIDs with open transactions)
B - Blocking / blocked sessions only
S - Exclude sleeping SPIDs with open transactions
X - Exclude system processes
@Database_Name : Limit the result set to a specific database (use ---------- for NULL database names)
@Exclude_Lock : Suppress lock details from the output (can increases procedure performance on busy servers; defaulted to 1)
@Exclude_Log : Suppress log details from the output (can increases procedure performance on busy servers; defaulted to 1)
@Exclude_Plan : Suppress execution plan details from the output (can increases procedure performance on busy servers; defaulted to 1)
@Exclude_SQL : Suppress SQL statement details from the output (can increases procedure performance on busy servers; defaulted to 0)
@Exclude_SQL_XML : Suppress SQL statement XML details from the output (can increases procedure performance on busy servers; defaulted to 1)
@Exclude_TXN : Suppress transaction details from the output (also suppresses log details due to an interdependency; can increases procedure performance on busy servers; defaulted to 1)
@Login : Limit the result set to a specific Windows user name (if populated, otherwise by SQL Server login name)
@SPID : Limit the result set to a specific session
Notes:
Blocking / blocked sessions will always be displayed first in the result set (when applicable)
Output:
SPID : System Process ID
Database_Name : Database context of the session
Running : Indicates if the session is executing (X), waiting ([]), inactive (blank), inactive with open transactions (•), a background task (--), or not defined (N/A)
Blocking : Blocking indicator (includes type of block, SPID list, and deadlock detection when applicable)
Status : Status of the session -> request
Object_Name : Object being referenced (blank for ad hoc and prepared statements)
Command : Command executed
Threads : Process thread count
SQL_Statement_Batch : Batch statement of the session
SQL_Statement_Current : Current statement of the session
Isolation_Level : Isolation level of the session
Wait_Time : Current wait time (DAYS HH:MM:SS)
Wait_Type : Current wait type
Last_Wait_Type : Previous wait type
Elapsed_Time : Elapsed time since the request began (DAYS HH:MM:SS)
CPU_Total : CPU time used since login (DAYS HH:MM:SS)
CPU_Current : CPU time used for the current process (DAYS HH:MM:SS)
Logical_Reads_Total : Logical reads performed since login
Logical_Reads_Current : Logical reads performed by the current process
Physical_Reads_Total : Physical reads performed since login
Physical_Reads_Current : Physical reads performed by the current process
Writes_Total : Writes performed since login
Writes_Current : Writes performed by the current process
Last_Row_Count : Row count produced by the last statement executed
Allocated_Memory_MB : Memory allocated to the query in megabytes
Pages_Used : Pages in the procedure cache allocated to the process
Transactions : Open transactions for the process
Transaction_ID : Transaction ID
Transaction_Time : Elapsed time since the transaction began (DAYS HH:MM:SS)
Transaction_Type : Type of transaction
Transaction_State : State of the transaction
Nesting_Level : Nesting level of the statement executing
TempDB_Session_Total_MB : Temp DB space used since login for the session in megabytes
TempDB_Session_Current_MB : Temp DB space currently used by the session in megabytes
TempDB_Task_Total_MB : Temp DB space used by the entire task in megabytes
TempDB_Task_Current_MB : Temp DB space currently used by the task in megabytes
Log_Database_Count : Databases involved in the transaction
Log_Records_All : Log records generated for the transaction (all databases)
Log_Reserved_MB_All : Log space reserved for the transaction in megabytes (all databases)
Log_Used_MB_All : Log space used for the transaction in megabytes (all databases)
Log_Details : Log usage details for the transaction per database (in XML format)
Lock_Timeout_Seconds : Lock timeout of the session
Lock_Details : Lock details of the session (in XML format)
Deadlock_Priority : Deadlock priority of the session
SQL_Statement_Batch_XML : Same as "SQL_Statement_Batch" but in XML format
SQL_Statement_Current_XML : Same as "SQL_Statement_Current" but in XML format
SQL_Handle : Identifier for the executing batch or object
Query_Plan : Execution plan of the session (in XML format)
Plan_Handle : Identifier for the in-memory plan
Since_SPID_Login : Elapsed time since the client logged in (DAYS HH:MM:SS)
Since_Last_Batch_Start : Elapsed time since the last request began (DAYS HH:MM:SS)
Since_Last_Batch_End : Elapsed time since the last completion of a request (DAYS HH:MM:SS)
Command_Pct : Percentage of work completed (applies to a limited set of commands)
Command_Completion : Estimated completion time for the command
Command_Time_Left : Time left before the command completes (DAYS HH:MM:SS)
Host_Name : Name of the client workstation specific to a session
Login_ID : Windows user name (or "Login_Name" if user name is unavailable)
Login_Name : Full name of the user associated to the "Login_ID"
Application_Description : Application accessing SQL Server
System_Process : Indicates if the session is a system process
SPID : System Process ID
'
PRINT SUBSTRING (@Print, 1, 3931)
PRINT SUBSTRING (@Print, 3934, 4000)
RETURN
END
-----------------------------------------------------------------------------------------------------------------------------
-- Error Trapping: Check If Temp Table(s) Already Exist(s) And Drop If Applicable
-----------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID (N'tempdb.dbo.#temp_core_data', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#temp_core_data
END
IF OBJECT_ID (N'tempdb.dbo.#temp_databases', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#temp_databases
END
IF OBJECT_ID (N'tempdb.dbo.#temp_deadlocking', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#temp_deadlocking
END
IF OBJECT_ID (N'tempdb.dbo.#temp_false_positive_blocking', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#temp_false_positive_blocking
END
IF OBJECT_ID (N'tempdb.dbo.#temp_lock_details', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#temp_lock_details
END
IF OBJECT_ID (N'tempdb.dbo.#temp_log_details', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#temp_log_details
END
IF OBJECT_ID (N'tempdb.dbo.#temp_parallelism', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#temp_parallelism
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Creation: Create Various Temp Tables
-----------------------------------------------------------------------------------------------------------------------------
CREATE TABLE dbo.#temp_databases
(
database_id INT NULL
,database_name NVARCHAR (128) NULL
)
CREATE TABLE dbo.#temp_lock_details
(
req_spid INT NULL
,rsc_dbid SMALLINT NULL
,rsc_objid INT NULL
,rsc_indid SMALLINT NULL
,[object_name] NVARCHAR (275) NULL
,index_name NVARCHAR (128) NULL
,rsc_type TINYINT NULL
,req_mode TINYINT NULL
,req_status TINYINT NULL
,req_ownertype SMALLINT NULL
,req_ecid INT NULL
,req_refcnt INT NULL
)
CREATE TABLE dbo.#temp_log_details
(
transaction_id BIGINT NULL
,database_id INT NULL
,database_transaction_begin_time DATETIME NULL
,database_transaction_type INT NULL
,database_transaction_state INT NULL
,database_transaction_log_record_count BIGINT NULL
,database_transaction_log_bytes_reserved BIGINT NULL
,database_transaction_log_bytes_used BIGINT NULL
,database_transaction_log_bytes_reserved_system INT NULL
,database_transaction_log_bytes_used_system INT NULL
)
-----------------------------------------------------------------------------------------------------------------------------
-- Table Insert: Databases
-----------------------------------------------------------------------------------------------------------------------------
SET @Database_ID = -2147483648
SET LOCK_TIMEOUT 5
WHILE @Database_ID IS NOT NULL
BEGIN
BEGIN TRY
INSERT INTO dbo.#temp_databases
(
database_id
,database_name
)
SELECT TOP (1)
DB.database_id
,DB.name AS database_name
FROM
master.sys.databases DB
WHERE
DB.database_id = @Database_ID
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
SET @Database_ID = (SELECT TOP (1) DB.database_id FROM master.sys.databases DB WHERE DB.database_id > @Database_ID ORDER BY DB.database_id)
END TRY
BEGIN CATCH
SET @Database_ID = @Database_ID + 1
END CATCH
END
SET LOCK_TIMEOUT -1
-----------------------------------------------------------------------------------------------------------------------------
-- Table Insert: Core Data
-----------------------------------------------------------------------------------------------------------------------------
SELECT
DXS.session_id
,ttDB.database_name
,DER.blocking_session_id
,DXS.[status] AS status_session
,DER.[status] AS status_request
,CONVERT (INT, NULL) AS [dbid]
,CONVERT (INT, NULL) AS objectid
,CONVERT (NVARCHAR (275), NULL) AS [object_name]
,DER.command
,sqSP.threads
,CONVERT (NVARCHAR (MAX), NULL) AS [text]
,sqSP.stmt_start
,sqSP.stmt_end
,DXS.transaction_isolation_level
,DER.wait_time
,DER.wait_type
,DER.last_wait_type
,DER.total_elapsed_time
,DXS.cpu_time AS cpu_time_total
,DER.cpu_time AS cpu_time_current
,DXS.logical_reads AS logical_reads_total
,DER.logical_reads AS logical_reads_current
,DXS.reads AS reads_total
,DER.reads AS reads_current
,DXS.writes AS writes_total
,DER.writes AS writes_current
,DXS.row_count
,DER.granted_query_memory
,DXS.memory_usage
,sqSP.open_tran
,CONVERT (BIGINT, NULL) AS transaction_id
,CONVERT (DATETIME, NULL) AS transaction_begin_time
,CONVERT (INT, NULL) AS transaction_type
,CONVERT (INT, NULL) AS transaction_state
,DER.nest_level
,sqTS.tempdb_page_allocation_session
,sqTS.tempdb_page_deallocation_session
,sqTT.tempdb_page_allocation_task
,sqTT.tempdb_page_deallocation_task
,DXS.[lock_timeout]
,DXS.[deadlock_priority]
,sqSP.[sql_handle]
,CONVERT (XML, NULL) AS query_plan
,DER.plan_handle
,DXS.login_time AS login_time_sessions
,sqSP.login_time AS login_time_processes
,DXS.last_request_start_time
,DXS.last_request_end_time
,sqSP.last_batch
,DER.percent_complete
,DER.estimated_completion_time
,DXS.[host_name]
,DXS.nt_user_name
,DXS.login_name
,DXS.[program_name]
,DXS.is_user_process
INTO
dbo.#temp_core_data
FROM
master.sys.dm_exec_sessions DXS
INNER JOIN
(
SELECT
SP.spid
,SUM (CASE
WHEN SP.kpid = 0 THEN 0
ELSE 1
END) AS threads
,MAX (SP.stmt_start) AS stmt_start
,MAX (SP.stmt_end) AS stmt_end
,MAX (SP.open_tran) AS open_tran
,MAX (NULLIF (SP.[sql_handle], 0x0000000000000000000000000000000000000000)) AS [sql_handle]
,MAX (SP.login_time) AS login_time
,MAX (SP.last_batch) AS last_batch
,MAX (SP.[dbid]) AS [dbid]
FROM
master.sys.sysprocesses SP
GROUP BY
SP.spid
) sqSP ON sqSP.spid = DXS.session_id
LEFT JOIN master.sys.dm_exec_requests DER ON DER.session_id = DXS.session_id
LEFT JOIN dbo.#temp_databases ttDB ON ttDB.database_id = sqSP.[dbid]
LEFT JOIN
(
SELECT
DDSSU.session_id
,SUM (DDSSU.user_objects_alloc_page_count + DDSSU.internal_objects_alloc_page_count) AS tempdb_page_allocation_session
,SUM (DDSSU.user_objects_dealloc_page_count + DDSSU.internal_objects_dealloc_page_count) AS tempdb_page_deallocation_session
FROM
master.sys.dm_db_session_space_usage DDSSU
GROUP BY
DDSSU.session_id
) sqTS ON sqTS.session_id = DXS.session_id
LEFT JOIN
(
SELECT
DDTSU.session_id
,SUM (DDTSU.user_objects_alloc_page_count + DDTSU.internal_objects_alloc_page_count) AS tempdb_page_allocation_task
,SUM (DDTSU.user_objects_dealloc_page_count + DDTSU.internal_objects_dealloc_page_count) AS tempdb_page_deallocation_task
FROM
master.sys.dm_db_task_space_usage DDTSU
GROUP BY
DDTSU.session_id
) sqTT ON sqTT.session_id = DXS.session_id
WHERE
(
(
(
@Database_Name IS NULL
OR ISNULL (ttDB.database_name, N'----------') = @Database_Name
)
AND
(
@Filter_Active = 0
OR (CASE
WHEN @Filter_Sleeping = 0 AND sqSP.open_tran > 0 THEN N''
ELSE DXS.[status]
END) NOT IN (N'dormant', N'sleeping')
)
AND
(
@Filter_Blocked = 0
OR DER.blocking_session_id <> 0
)
AND
(
@Filter_System = 0
OR DXS.is_user_process = 1
)
AND
(
@Login IS NULL
OR DXS.nt_user_name = @Login
OR DXS.login_name = @Login
)
AND
(
@SPID IS NULL
OR DXS.session_id = @SPID
)
)
OR
(
NULLIF (DER.blocking_session_id, 0) IS NOT NULL
OR EXISTS
(
SELECT
*
FROM
master.sys.dm_exec_requests XDER
WHERE
XDER.blocking_session_id <> 0
AND XDER.blocking_session_id = DXS.session_id
)
)
)
-----------------------------------------------------------------------------------------------------------------------------
-- Table Update: Populate Transaction Details
-----------------------------------------------------------------------------------------------------------------------------
IF @Exclude_TXN = 0
BEGIN
UPDATE
ttCD
SET
ttCD.transaction_id = DTST.transaction_id
,ttCD.transaction_begin_time = DTAT.transaction_begin_time
,ttCD.transaction_type = DTAT.transaction_type
,ttCD.transaction_state = DTAT.transaction_state
FROM
dbo.#temp_core_data ttCD
INNER JOIN master.sys.dm_tran_session_transactions DTST ON DTST.session_id = ttCD.session_id
LEFT JOIN master.sys.dm_tran_active_transactions DTAT ON DTAT.transaction_id = DTST.transaction_id
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Insert: Transaction Log Details
-----------------------------------------------------------------------------------------------------------------------------
IF @Exclude_Log = 0 AND @Exclude_TXN = 0
BEGIN
INSERT INTO dbo.#temp_log_details
(
transaction_id
,database_id
,database_transaction_begin_time
,database_transaction_type
,database_transaction_state
,database_transaction_log_record_count
,database_transaction_log_bytes_reserved
,database_transaction_log_bytes_used
,database_transaction_log_bytes_reserved_system
,database_transaction_log_bytes_used_system
)
SELECT
DTDT.transaction_id
,DTDT.database_id
,DTDT.database_transaction_begin_time
,DTDT.database_transaction_type
,DTDT.database_transaction_state
,DTDT.database_transaction_log_record_count
,DTDT.database_transaction_log_bytes_reserved
,DTDT.database_transaction_log_bytes_used
,DTDT.database_transaction_log_bytes_reserved_system
,DTDT.database_transaction_log_bytes_used_system
FROM
master.sys.dm_tran_database_transactions DTDT
WHERE
EXISTS
(
SELECT
*
FROM
dbo.#temp_core_data ttCD
WHERE
ttCD.transaction_id = DTDT.transaction_id
)
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Insert: Lock Request Details
-----------------------------------------------------------------------------------------------------------------------------
IF @Exclude_Lock = 0
BEGIN
INSERT INTO dbo.#temp_lock_details
(
req_spid
,rsc_dbid
,rsc_objid
,rsc_indid
,[object_name]
,index_name
,rsc_type
,req_mode
,req_status
,req_ownertype
,req_ecid
,req_refcnt
)
SELECT
SLI.req_spid
,SLI.rsc_dbid
,SLI.rsc_objid
,SLI.rsc_indid
,CONVERT (NVARCHAR (275), NULL) AS [object_name]
,CONVERT (NVARCHAR (128), NULL) AS index_name
,SLI.rsc_type
,SLI.req_mode
,SLI.req_status
,SLI.req_ownertype
,SLI.req_ecid
,SUM (SLI.req_refcnt) AS req_refcnt
FROM
master.sys.syslockinfo SLI
WHERE
EXISTS
(
SELECT
*
FROM
dbo.#temp_core_data ttCD
WHERE
ttCD.session_id = SLI.req_spid
)
GROUP BY
SLI.req_spid
,SLI.rsc_dbid
,SLI.rsc_objid
,SLI.rsc_indid
,SLI.rsc_type
,SLI.req_mode
,SLI.req_status
,SLI.req_ownertype
,SLI.req_ecid
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Update: Attempt To Populate SQL Text Data And Object Details
-----------------------------------------------------------------------------------------------------------------------------
IF @Exclude_SQL = 0
BEGIN
SET @SQL_Handle = (SELECT TOP (1) ttCD.[sql_handle] FROM dbo.#temp_core_data ttCD WHERE ttCD.[sql_handle] IS NOT NULL ORDER BY ttCD.[sql_handle])
WHILE @SQL_Handle IS NOT NULL
BEGIN
SET LOCK_TIMEOUT 5
BEGIN TRY
UPDATE
ttCD
SET
ttCD.[dbid] = (CASE
WHEN ttCD.[dbid] IS NULL AND ttCD.objectid IS NULL THEN DEST.[dbid]
ELSE ttCD.[dbid]
END)
,ttCD.objectid = (CASE
WHEN ttCD.[dbid] IS NULL AND ttCD.objectid IS NULL THEN DEST.objectid
ELSE ttCD.objectid
END)
,ttCD.[text] = DEST.[text]
FROM
dbo.#temp_core_data ttCD
CROSS APPLY master.sys.dm_exec_sql_text (ttCD.[sql_handle]) DEST
WHERE
ttCD.[sql_handle] = @SQL_Handle
END TRY
BEGIN CATCH
END CATCH
SET LOCK_TIMEOUT -1
SET @SQL_Handle = (SELECT TOP (1) ttCD.[sql_handle] FROM dbo.#temp_core_data ttCD WHERE ttCD.[sql_handle] IS NOT NULL AND ttCD.[sql_handle] > @SQL_Handle ORDER BY ttCD.[sql_handle])
END
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Update: Attempt To Populate Query Plan Data And Object Details
-----------------------------------------------------------------------------------------------------------------------------
IF @Exclude_Plan = 0
BEGIN
SET @Plan_Handle = (SELECT TOP (1) ttCD.plan_handle FROM dbo.#temp_core_data ttCD WHERE ttCD.plan_handle IS NOT NULL ORDER BY ttCD.plan_handle)
WHILE @Plan_Handle IS NOT NULL
BEGIN
SET LOCK_TIMEOUT 5
BEGIN TRY
UPDATE
ttCD
SET
ttCD.[dbid] = (CASE
WHEN ttCD.[dbid] IS NULL AND ttCD.objectid IS NULL THEN DEQP.[dbid]
ELSE ttCD.[dbid]
END)
,ttCD.objectid = (CASE
WHEN ttCD.[dbid] IS NULL AND ttCD.objectid IS NULL THEN DEQP.objectid
ELSE ttCD.objectid
END)
,ttCD.query_plan = DEQP.query_plan
FROM
dbo.#temp_core_data ttCD
CROSS APPLY master.sys.dm_exec_query_plan (ttCD.plan_handle) DEQP
WHERE
ttCD.plan_handle = @Plan_Handle
END TRY
BEGIN CATCH
END CATCH
SET LOCK_TIMEOUT -1
SET @Plan_Handle = (SELECT TOP (1) ttCD.plan_handle FROM dbo.#temp_core_data ttCD WHERE ttCD.plan_handle IS NOT NULL AND ttCD.plan_handle > @Plan_Handle ORDER BY ttCD.plan_handle)
END
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Update: Attempt To Populate Object Name
-----------------------------------------------------------------------------------------------------------------------------
IF (@Exclude_Plan = 0 OR @Exclude_SQL = 0)
BEGIN
SET @Database_ID = (SELECT TOP (1) ttCD.[dbid] FROM dbo.#temp_core_data ttCD WHERE ttCD.[dbid] IS NOT NULL AND ttCD.objectid IS NOT NULL ORDER BY ttCD.[dbid])
WHILE @Database_ID IS NOT NULL
BEGIN
SET @SQL_String =
N'
USE [' + (SELECT ttDB.database_name FROM dbo.#temp_databases ttDB WHERE ttDB.database_id = @Database_ID) + N']
UPDATE
ttCD
SET
ttCD.[object_name] = N''['' + S.name + N''].['' + AO.name + N'']''
FROM
dbo.#temp_core_data ttCD
INNER JOIN sys.all_objects AO ON AO.[object_id] = ttCD.objectid
INNER JOIN sys.schemas S ON S.[schema_id] = AO.[schema_id]
WHERE
ttCD.[dbid] = ' + CONVERT (NVARCHAR (11), @Database_ID) + N'
'
IF @SQL_String IS NOT NULL
BEGIN
SET LOCK_TIMEOUT 5
BEGIN TRY
EXECUTE (@SQL_String)
END TRY
BEGIN CATCH
END CATCH
SET LOCK_TIMEOUT -1
END
SET @Database_ID = (SELECT TOP (1) ttCD.[dbid] FROM dbo.#temp_core_data ttCD WHERE ttCD.[dbid] IS NOT NULL AND ttCD.objectid IS NOT NULL AND ttCD.[dbid] > @Database_ID ORDER BY ttCD.[dbid])
END
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Update: Attempt To Populate Lock Details' Database Name / Object Name / Index Name
-----------------------------------------------------------------------------------------------------------------------------
IF @Exclude_Lock = 0
BEGIN
SET @Database_ID = (SELECT TOP (1) ttLKD.rsc_dbid FROM dbo.#temp_lock_details ttLKD ORDER BY ttLKD.rsc_dbid)
WHILE @Database_ID IS NOT NULL
BEGIN
SET @SQL_String =
N'
USE [' + (SELECT ttDB.database_name FROM dbo.#temp_databases ttDB WHERE ttDB.database_id = @Database_ID) + N']
UPDATE
ttLKD
SET
ttLKD.[object_name] = N''['' + S.name + N''].['' + AO.name + N'']''
,ttLKD.index_name = I.name
FROM
dbo.#temp_lock_details ttLKD
LEFT JOIN sys.all_objects AO ON AO.[object_id] = ttLKD.rsc_objid
LEFT JOIN sys.schemas S ON S.[schema_id] = AO.[schema_id]
LEFT JOIN sys.indexes I ON I.[object_id] = ttLKD.rsc_objid
AND I.index_id = ttLKD.rsc_indid
WHERE
ttLKD.rsc_dbid = ' + CONVERT (NVARCHAR (11), @Database_ID) + N'
'
IF @SQL_String IS NOT NULL
BEGIN
SET LOCK_TIMEOUT 5
BEGIN TRY
EXECUTE (@SQL_String)
END TRY
BEGIN CATCH
END CATCH
SET LOCK_TIMEOUT -1
END
SET @Database_ID = (SELECT TOP (1) ttLKD.rsc_dbid FROM dbo.#temp_lock_details ttLKD WHERE ttLKD.rsc_dbid > @Database_ID ORDER BY ttLKD.rsc_dbid)
END
END
-----------------------------------------------------------------------------------------------------------------------------
-- Table Insert: Identify False Positive Blocking Cause By Timing Issues
-----------------------------------------------------------------------------------------------------------------------------
SELECT
ttCD.session_id
,(CASE
WHEN caCB.matches_filter_criteria = 0 AND caCB.is_truly_blocked = 0 AND caCB.is_truly_blocking = 0 THEN N'D'
ELSE N'U'
END) AS modification_type
INTO
dbo.#temp_false_positive_blocking
FROM
dbo.#temp_core_data ttCD
LEFT JOIN dbo.#temp_core_data ttXCD ON ttXCD.session_id = ttCD.blocking_session_id
LEFT JOIN
(
SELECT DISTINCT
ttCD.blocking_session_id
FROM
dbo.#temp_core_data ttCD
) sqBS ON sqBS.blocking_session_id = ttCD.session_id