得到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 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述