Sqlserver-dba.com

SQL Server sql_handle returns sql statement

Certain Dynamic Management Views(DMV)  return a sql_handle column . 

Examples of DMVs returning the sql_handle column are :

sys.dm_exec_query_stats

sys.dm_exec_requests

 sql_handle is a varbinary(64)  . A varbinary is suitable  for variable length binary data.  The sql_handle is a token referencing a stored procedure or batch.

The table-valued function sys.dm_exec_sql_text returns the text of the sql_handle. It has a parameter : @handle  (varbinary(64))

 

--returns sql query text referencing aggregate performance statistics

-- on sys.dm_exec_query_stats.

select sql_handle,(SELECT TOP 1 SUBSTRING(s2.text,statement_start_offset / 2+1 ,

      ( (CASE WHEN statement_end_offset = -1

         THEN (LEN(CONVERT(nvarchar(max),s2.text)) * 2)

         ELSE statement_end_offset END)  - statement_start_offset) / 2+1))  AS sql_statement from sys.dm_exec_query_stats

CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2 
Author: Jack Vamvas (http://www.sqlserver-dba.com)

Author: Jack Vamvas (http://www.sqlserver-dba.com)

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact