sql 显示SQL Server会话运行代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 显示SQL Server会话运行代码相关的知识,希望对你有一定的参考价值。

-- 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:

以上是关于sql 显示SQL Server会话运行代码的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server扩展事件-- 使用system_health默认跟踪会话监控死锁

sql server 性能调优之 当前用户请求分析

sql server 表变量表类型临时表

SQL Server 中 sp_who 状态的含义

SQL Server Alwayson可用性副本会话期间的可能故障

sql server 2000