Sql Server 查看当前正在执行的Sql 语句

查看Sql Server 当前正在执行的Sql 语句,可以使用 sys.sysprocesses 或 sys.dm_exec_requests,由于sys.sysprocesses是为了向后兼容而保留的,所以,推荐使用DMV:sys.dm_exec_requests

一,使用sys.sysprocesses

Contains information about processes that are running on an instance of SQL Server. These processes can be client processes or system processes. To access sysprocesses, you must be in the master database context, or you must use the master.dbo.sysprocesses three-part name.

select p.spid,p.kpid,p.blocked,p.waittime,p.lastwaittype,
    p.waitresource,p.dbid,p.uid,p.cpu,p.physical_io,p.memusage,
    p.open_tran,p.status,p.hostname,p.program_name,
    p.cmd,p.nt_domain,p.nt_username,p.loginame,
    p.stmt_start,p.stmt_end,p.request_id,
    s.objectid,s.text as SqlStatement
from sys.sysprocesses p with(NOLOCK)
outer apply sys.dm_exec_sql_text(p.sql_handle) s
where p.spid>50
    and p.lastwaittype<>‘MISCELLANEOUS‘
    and p.status<>‘sleeping‘
    and p.spid<>@@spid
order by p.physical_io desc

@@SPID 表示当前的spid

一般来说,SPID<=50是system session,SPID>50的是User Session

LastWaitType 为‘MISCELLANEOUS‘ 时,it is not used for any valid wait. It is simply the default wait in a list and isn‘t used to indicate any real waiting.

关于LastWaitType ,请查看 http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx

sql_handle 字段表示的查询的handle,当使用sys.dm_exec_sql_text函数获取Sql Statement时,Sql Server会对某些包含常量的查询语句“Auto-parameterized”,获取的Sql statement如下,

(@P1 int,@P2 int,@P3 datetime2(7),@P4 datetime2(7))
WITH CategoryIDs      AS
(SELECT B.CategoryID,
  .....

stmt_start和stmt_end 这两个字段用于标识“Auto-parameterized”增加的语句的开始和结尾。

二,推荐使用DMV:sys.dm_exec_requests,

select    r.session_id,r.blocking_session_id,
        r.request_id,r.start_time,r.status,r.command,
        st.dbid,st.objectid,st.text as SqlStatement,
        SUBSTRING (st.text,
                    r.statement_start_offset/2,
                    (CASE WHEN r.statement_end_offset = -1
                            THEN LEN(CONVERT(NVARCHAR(MAX), st.text)) * 2
                        ELSE r.statement_end_offset END
                        - r.statement_start_offset)/2
                    ) as IndividualQueryStatement,
        r.database_id,r.user_id,r.connection_id,
        r.wait_type,r.wait_time,r.last_wait_type,r.wait_resource,r.open_transaction_count,
        r.percent_complete,r.estimated_completion_time,
        r.cpu_time,r.total_elapsed_time,r.reads,r.writes,r.logical_reads,
        r.transaction_isolation_level,r.lock_timeout,r.deadlock_priority,r.row_count,
        r.granted_query_memory,p.query_plan
from sys.dm_exec_requests r
outer APPLY sys.dm_exec_sql_text(r.sql_handle) as st
outer apply sys.dm_exec_query_plan(r.plan_handle) as p
where r.last_wait_type<>‘MISCELLANEOUS‘
    and r.session_id>50

三,使用DMV:sys.dm_exec_requests查看数据库block的状态

DMV:sys.dm_exec_requests 提供两个非常重要的字段是session_id,blocking_session_id

blocking_session_id

ID of the session that is blocking the request. If this column is NULL, the request is not blocked, or the session information of the blocking session is not available (or cannot be identified).

-2 = The blocking resource is owned by an orphaned distributed transaction.

-3 = The blocking resource is owned by a deferred recovery transaction.

-4 = Session ID of the blocking latch owner could not be determined at this time because of internal latch state transitions.

SELECT  R.session_id AS BlockedSessionID ,
        S.session_id AS BlockingSessionID ,
        Q1.text AS BlockedSession_TSQL ,
        Q2.text AS BlockingSession_TSQL ,
        C1.most_recent_sql_handle AS BlockedSession_SQLHandle ,
        C2.most_recent_sql_handle AS BlockingSession_SQLHandle ,
        S.original_login_name AS BlockingSession_LoginName ,
        S.program_name AS BlockingSession_ApplicationName ,
        S.host_name AS BlockingSession_HostName
FROM  sys.dm_exec_requests AS R
INNER JOIN sys.dm_exec_sessions AS S ON R.blocking_session_id = S.session_id
INNER JOIN sys.dm_exec_connections AS C1 ON R.session_id = C1.most_recent_session_id
INNER JOIN sys.dm_exec_connections AS C2 ON S.session_id = C2.most_recent_session_id
CROSS APPLY sys.dm_exec_sql_text(C1.most_recent_sql_handle) AS Q1
CROSS APPLY sys.dm_exec_sql_text(C2.most_recent_sql_handle) AS Q2

Appendix

如果已经知道SPID,可以使用dbcc inputbuffer(spid)来获取spid执行的sql语句。

参考文档

https://msdn.microsoft.com/zh-cn/library/ms179881(v=sql.110).aspx

https://msdn.microsoft.com/ZH-CN/LIBRARY/ms177648

http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx

https://msdn.microsoft.com/en-us/library/ms176013(SQL.90).aspx

https://msdn.microsoft.com/en-us/library/ms181509.aspx

http://blog.csdn.net/dba_huangzj/article/details/8697578

时间: 2024-10-13 19:59:13

Sql Server 查看当前正在执行的Sql 语句的相关文章

SQL Server查询数据库近期执行的SQL语句

SELECT TOP 1000        ST.text AS '执行的SQL语句',       QS.execution_count AS '执行次数',       QS.total_elapsed_time AS '耗时',       QS.total_logical_reads AS '逻辑读取次数',       QS.total_logical_writes AS '逻辑写入次数',       QS.total_physical_reads AS '物理读取次数',    

SQL Server查看表结构及视图,适合开发者使用,简单易用

SELECT * FROM INFORMATION_SCHEMA.TABLES SELECT * FROM INFORMATION_SCHEMA.COLUMNS 查看执行结果 SQL Server查看表结构及视图,适合开发者使用,简单易用,布布扣,bubuko.com

SQL Server查看索引重建、重组索引进度

原文:SQL Server查看索引重建.重组索引进度 相信很多SQL Server DBA或开发人员在重建或重组大表索引时,都会相当郁闷,不知道索引重建的进度,这个对于DBA完全是一个黑盒子,对于系统负载非常大的系统或维护窗口较短的系统,你会遇到一些挑战.例如,你创建索引的时候,很多会话被阻塞,你只能取消创建索引的任务.查看这些索引维护操作的进度.预估时间对于我们有较大的意义,需要根据这个做一些决策.下面我们来看看看看如何获取CREATE INDEX.ALTER INDEX REBUILD.AL

如何查看PostgreSQL正在执行的SQL

SELECT      procpid,      start,      now() - start AS lap,      current_query  FROM      (SELECT          backendid,          pg_stat_get_backend_pid(S.backendid) AS procpid,          pg_stat_get_backend_activity_start(S.backendid) AS start,        

SQL SERVER 查看SQL语句IO,时间,索引消耗

1.查看SQL语句IO消耗 set statistics io on     select * from dbo.jx_order where order_time>'2011-04-12 12:49:57.580' set statistics io off 2.查看SQL语句时间消耗 set statistics time on      select * from dbo.jx_order where order_time>'2011-04-12 12:49:57.580' set st

sql server 查看列备注、类型、字段大小

select 列名 = a.name ,类型 = c.name ,长度 = columnproperty(a.id,a.name,'precision') ,备注 = g.value from syscolumns a left join sysobjects b on a.id=b.id left join systypes c on a.xusertype = c.xusertype left join sysproperties g on a.id =g.id and a.colid =g

Sql Server 查看所有存储过程或视图的位置及内容

原文:Sql Server 查看所有存储过程或视图的位置及内容 select a.name,a.[type],b.[definition] from sys.all_objects a,sys.sql_modules b where a.is_ms_shipped=0 and a.object_id = b.object_id and a.[type] in ('P','V','AF') order by a.[name] asc 通过这个sql语句可以查到sql server中的视图和存储过程

sql server 查看对象最后修改时间

sql server 查看对象最后修改时间,根据最后修改时间排序 存储过程 SELECT * FROM sys.all_objects WHERE  TYPE='P' ORDER BY modify_date DESC; 视图 SELECT * FROM sys.all_objects WHERE  TYPE='v' ORDER BY modify_date DESC; 表 SELECT * FROM sys.all_objects WHERE  TYPE='u' ORDER BY modify

SQL SERVER: 给用户增加执行存储过程的权限

USE DatabaseName GO CREATE ROLE UserName GO GRANT EXECUTE TO UserName GOSQL SERVER: 给用户增加执行存储过程的权限