solorez~Z Space

关注数据库,关注MS SQL Server

导航

得到SQLServer当前运行的语句

SP_WHO2是一个比较流行的SQL查看运行状态的函数,但是它有比较多的限制,比如我们只能看到命令类型,而不能查看具体内容,本文介绍的方法可以破除这种限制。

运行的效果如下:

原理分析

    我们可以从sys.dm_exec_requests视图中读取正在运行的请求,以及这个请求的句柄(sql_handle),通过句柄,可以从sys.dm_exec_sql_text得到请求的具体内容。同时,通过(SPID)联接sys.processes这个表,可以得到运行语句的用户、数据库、及应用程序名,所有的字段都在下表中列了出来:

Column name

Data type

Description

spid

smallint

SQL Server process ID.

ecid

smallint

Execution context ID used to uniquely identify the subthreads operating on behalf of a single process.

dbid

smallint

ID of the database currently being used by the process.

nt_username

nchar(128)

Windows user name for the process, if using Windows Authentication, or a trusted connection.

status

nchar(30)

Process ID status. For example, running and sleeping.

wait_type

bigint

Current wait time in milliseconds.

Individual Query

varchar

SQL Statement currently running.

Parent Query

varchar

Routine that contains the Individual Query.

program_name

nchar(128)

Name of the application program.

Hostname

nchar(128)

Name of the workstation.

nt_domain

nchar(128)

Microsoft Windows domain for the client, if using Windows Authentication, or a trusted connection.

Start_time

datetime

Time when the request is scheduled to run.

最后的SQL语句如下:

 

SELECT [Spid] = session_Id

    , ecid

    , [Database] = DB_NAME(sp.dbid)

    , [User] = nt_username

    , [Status] = er.status

    , [Wait] = wait_type

    , [Individual Query] = SUBSTRING (qt.text,

er.statement_start_offset/2,

    (CASE WHEN er.statement_end_offset = -1

     THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2

        ELSE er.statement_end_offset END -

er.statement_start_offset)/2)

    ,[Parent Query] = qt.text

    , Program = program_name

    , Hostname

    , nt_domain

    , start_time

FROM sys.dm_exec_requests er

INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid

CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt

WHERE session_Id > 50 -- Ignore system spids.

AND session_Id NOT IN (@@SPID) -- Ignore this current statement.

ORDER BY 1, 2

   

原文地址:http://www.sqlservercentral.com/articles/DMV/64425/

posted on 2008-11-28 16:59  付博  阅读(1567)  评论(0编辑  收藏  举报