sql server 正在运行的sql语句

本文涉及的产品
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云数据库 RDS SQL Server,基础系列 2核4GB
简介:

Introduction

sp_who2 is a well known utility that shows what spids are currently executing. However the information it shows is relatively limited. For example, it only shows the type of command executing as SELECT, DELETE etc, with no reference to the actual underlying SQL executing.

Knowing what SQL is executing can be vital in debugging why a query is taking a long time, or determining if it is being blocked. It can also be useful in showing the progress of a stored procedure i.e. what statement within the stored procedure is currently executing.

The utility described in this article will obviate these limitations of sp_who2.

The utility makes use of Dynamic Management Views (DMVs), so can be used by SQL Server 2005 or greater.

What SQL Statements Are Currently Executing Utility

The SQL used in this utility ‘dba_WhatSQLIsExecuting’ is given in Listing 1.

The Dynamic Management View (DMV) sys.db_exec_requests shows which requests are currently executing, the information shown includes the handle to the whole SQL text of the batch or stored procedure (sql_handle), together with offsets relating to the section of SQL within the batch that is currently executing (statement_start_offset and statement_end_offset).

To determine the current section of SQL currently executing, we need to call the Dynamic Management Function (DMF) sys.dm_exec_sql_text, passing in the handle of the SQL batch that is currently executing, and then apply the relevant offsets.

We can get more information about the query by combining the sys.db_exec_requests DMV with the sys.processes system view (joined on spid/session_id). This information includes who is executing the query, the machine they are running from, and the name of the database.

The utility selects relevant fields from the sys.db_exec_requests and sys.sysprocesses views. The selected fields are described in figure 1 (largely taken from SQL Server 2005 Books online).

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.

Figure 1 Columns in the ‘What SQL Statements Are Executing’ utility.

Running the utility on my SQL Server gives the results given in Figure 2.

Figure 2 Output from the ‘What SQL Statements Are Executing’ utility.

The results show the Parent Query that is running (typically a stored procedure), together with the Individual Query within the Parent Query that is currently executing. Additional useful information (e.g. database name, user name etc) is also shown.

Discussion

This utility allows you to observe the progress of a stored procedure or SQL batch, additionally it can be used to identify the cause of a long running query or blocking query.

Since the utility uses existing data held in DMVs it is relatively non-intrusive and should have little affect on performance.

If the identified queries are long running or causing blocking, it might be worthwhile running them inside the Database Tuning Advisor (DTA), this might identify the cause of the slow running (e.g. a missing index).

Further work

It is possible to extend this utility to report only on the database you are interested in, by providing a filter based on database name or database id.

It might be interesting to use the output to drive a trace and/or process-flow engine. This will report on process flow through a stored procedure, and could be useful in determining how much code has been hit/missed during testing, as well as getting a view on what code is executed for a given run/set of parameters.

Conclusion

The utility described in this article will allow you to identify what SQL statements are currently executing. This information can be useful in debugging the cause of both long running queries and blocking, and should prove valuable in the everyday work of the SQL Server DBA/developer.

Credits

Ian Stirkhas been working in IT as a developer, designer, and architect since 1987. He holds the following qualifications: M.Sc., MCSD.NET, MCDBA, and SCJP. He is a freelance consultant working with Microsoft technologies in London England. He can be contacted at Ian_Stirk@yahoo.com.

Code

复制代码

   
   
CREATE PROC [ dbo ] . [ dba_WhatSQLIsExecuting ]
AS
/* --------------------------------------------------------------------
Purpose: Shows what individual SQL statements are currently executing.
----------------------------------------------------------------------
Parameters: None.
Revision History:
24/07/2008 Ian_Stirk@yahoo.com Initial version
Example Usage:
1. exec YourServerName.master.dbo.dba_WhatSQLIsExecuting
---------------------------------------------------------------------
*/
BEGIN
-- Do not lock anything, and do not get held up by any locks.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

-- What SQL Statements Are Currently Running?
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
END
复制代码
from  http://www.sqlservercentral.com/articles/DMV/64425/
分类:  MSSQL



    本文转自 Fanr_Zh 博客园博客,原文链接:http://www.cnblogs.com/Amaranthus/archive/2011/04/01/2002004.html ,如需转载请自行联系原作者


相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情: https://www.aliyun.com/product/rds/sqlserver
相关文章
|
2月前
|
SQL 关系型数据库 MySQL
拖.sql文件到cmd中运行
通过命令行工具cmd来运行SQL脚本文件,包括登录MySQL数据库、选择数据库和使用source命令执行脚本文件的步骤。
38 0
|
21天前
|
SQL 存储 BI
gbase 8a 数据库 SQL合并类优化——不同数据统计周期合并为一条SQL语句
gbase 8a 数据库 SQL合并类优化——不同数据统计周期合并为一条SQL语句
|
2月前
|
SQL 关系型数据库 MySQL
详解 pypika 模块:SQL 语句生成器,让你再也不用为拼接 SQL 语句而发愁
详解 pypika 模块:SQL 语句生成器,让你再也不用为拼接 SQL 语句而发愁
183 4
|
2月前
|
SQL 数据库
执行 Transact-SQL 语句或批处理时发生了异常。 (Microsoft.SqlServer.ConnectionInfo)之解决方案
执行 Transact-SQL 语句或批处理时发生了异常。 (Microsoft.SqlServer.ConnectionInfo)之解决方案
354 0
|
2月前
|
SQL 存储 缓存
一条 SQL 查询语句是如何运行?
本文详细剖析了SQL语句在MySQL中的执行流程,涵盖客户端、Server层及存储引擎层。Server层包括连接器、查询缓存、分析器、优化器与执行器等核心组件。连接器管理连接与权限校验,查询缓存加速查询,分析器负责词法与语法分析,优化器提升SQL性能,执行器调用存储引擎接口。了解这些流程有助于深入理解MySQL内部机制及其优化原理。
49 0
|
4月前
|
SQL XML 运维
SQL Server 运维常用sql语句(三)
SQL Server 运维常用sql语句(三)
30 1
|
4月前
|
Java 应用服务中间件 Maven
从零到英雄:一步步构建你的首个 JSF 应用程序,揭开 JavaServer Faces 的神秘面纱
【8月更文挑战第31天】JavaServer Faces (JSF) 是一种强大的 Java EE 标准,用于构建企业级 Web 应用。它提供了丰富的组件库和声明式页面描述语言 Facelets,便于开发者快速开发功能完善且易于维护的 Web 应用。本文将指导你从零开始构建一个简单的 JSF 应用,包括环境搭建、依赖配置、Managed Bean 编写及 Facelets 页面设计。
107 0
|
4月前
|
SQL 关系型数据库 MySQL
【超全整理】SQL日期与时间函数大汇总会:MySQL与SQL Server双轨对比教学,助你轻松搞定时间数据处理难题!
【8月更文挑战第31天】本文介绍了在不同SQL数据库系统(如MySQL、SQL Server、Oracle)中常用的日期与时间函数,包括DATE、NOW()、EXTRACT()、DATE_ADD()、TIMESTAMPDIFF()及日期格式化等,并提供了具体示例。通过对比这些函数在各系统中的使用方法,帮助开发者更高效地处理日期时间数据,满足多种应用场景需求。
546 0
|
4月前
|
SQL 关系型数据库 MySQL
SQL Server、MySQL、PostgreSQL:主流数据库SQL语法异同比较——深入探讨数据类型、分页查询、表创建与数据插入、函数和索引等关键语法差异,为跨数据库开发提供实用指导
【8月更文挑战第31天】SQL Server、MySQL和PostgreSQL是当今最流行的关系型数据库管理系统,均使用SQL作为查询语言,但在语法和功能实现上存在差异。本文将比较它们在数据类型、分页查询、创建和插入数据以及函数和索引等方面的异同,帮助开发者更好地理解和使用这些数据库。尽管它们共用SQL语言,但每个系统都有独特的语法规则,了解这些差异有助于提升开发效率和项目成功率。
480 0
|
3月前
|
SQL 数据库
数据库数据恢复—SQL Server数据库报错“错误823”的数据恢复案例
SQL Server附加数据库出现错误823,附加数据库失败。数据库没有备份,无法通过备份恢复数据库。 SQL Server数据库出现823错误的可能原因有:数据库物理页面损坏、数据库物理页面校验值损坏导致无法识别该页面、断电或者文件系统问题导致页面丢失。
107 12
数据库数据恢复—SQL Server数据库报错“错误823”的数据恢复案例