SQL server running SQL statement

Source: Internet
Author: User
Tags time in milliseconds what sql
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 should des 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 provided des 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.

Zoom in | open in New window

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 shoshould 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 cocould 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 shocould prove valuable in the everyday work of the SQL Server DBA/developer.

Credits

Ian stirkhas been working in it as a developer, designer, and effecect 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/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.