Created
February 25, 2016 22:17
-
-
Save NoahDragon/b5b024ac7db5ec51e099 to your computer and use it in GitHub Desktop.
Show SQL Server Session Running Code
This file contains hidden or 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
-- sp_who2 60 | |
-- DBCC OPENTRAN() -- check open transactions in DB | |
SET NOCOUNT ON | |
DECLARE @SPID SMALLINT | |
DECLARE @WAIT TINYINT | |
DECLARE @NoLoop BIT | |
SET @SPID = 81 -- MODIFY to correct SPID. | |
SET @WAIT = 0 | |
SET @NoLoop = 1 | |
DECLARE @sql_handle BINARY(20) | |
DECLARE @handle_found BIT | |
DECLARE @stmt_start INT | |
DECLARE @stmt_end INT | |
DECLARE @line NVARCHAR(4000) | |
DECLARE @wait_str VARCHAR(8) | |
SET @handle_found = 0 | |
IF @WAIT NOT BETWEEN 0 AND 60 | |
BEGIN | |
RAISERROR('Valid values for @WAIT are from 0 to 60 seconds', 16, 1) | |
RETURN | |
END | |
ELSE | |
BEGIN | |
SET @wait_str = '00:00:' + RIGHT('00' + CAST(@WAIT AS varchar(2)), 2) | |
END | |
WHILE 1 = 1 | |
BEGIN | |
SELECT @sql_handle = sql_handle, | |
@stmt_start = stmt_start/2, | |
@stmt_end = CASE WHEN stmt_end = -1 THEN -1 ELSE stmt_end/2 END | |
FROM master.dbo.sysprocesses | |
WHERE spid = @SPID | |
AND ecid = 0 | |
IF @sql_handle = 0x0 | |
/* | |
--If you are running this on SQL Server 2005, then change the above line to the following: | |
IF(@sql_handle = 0x0) OR (@stmt_start = 0 AND @stmt_end = 0) | |
--Without this change, this procedure might go into an infinite loop and needs to be killed | |
--In SQL Server 2000, as soon as a batch completed, | |
--the sql_handle column in sysprocesses becomes 0, but that's not the case in SQL Server 2005 | |
*/ | |
BEGIN | |
IF @handle_found = 0 | |
BEGIN | |
RAISERROR('Cannot find handle or the SPID is invalid', 16, 1) | |
RETURN | |
END | |
ELSE | |
BEGIN | |
RAISERROR('Query/Stored procedure completed', 0, 1) | |
RETURN | |
END | |
END | |
ELSE | |
BEGIN | |
SET @handle_found = 1 | |
END | |
SET @line = | |
( | |
SELECT SUBSTRING( text, | |
COALESCE(NULLIF(@stmt_start, 0), 1), | |
CASE | |
WHEN @stmt_end = -1 THEN DATALENGTH(text) | |
ELSE (@stmt_end - @stmt_start) | |
END | |
) | |
FROM ::fn_get_sql(@sql_handle) -- if deprecated, using sys.dm_exec_sql_text(@sql_handle) | |
) | |
RAISERROR(@line, 0, 1) WITH NOWAIT | |
IF @NoLoop = 1 | |
BEGIN | |
GOTO GET_OUT | |
END | |
WAITFOR DELAY @wait_str | |
END | |
GET_OUT: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment