SQL Handle to SQL Text

SQL Handle to SQL Text with Statement Start and Statement End:

DECLARE @sql_handle VARBINARY(64) ,
    @stmtstart INT ,
    @stmtend INT

SELECT  @stmtstart = 3268 ,
        @stmtend = 5102 ,
        @sql_handle = 0x03000800d8c3dd70e2f83f01e2a300000100000000000000

SELECT  SUBSTRING(qt.text, s.statement_start_offset / 2,
                  ( CASE WHEN s.statement_end_offset = -1
                         THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
                         ELSE s.statement_end_offset
                    END - s.statement_start_offset ) / 2) AS "SQL statement" ,
        s.statement_start_offset ,
        s.statement_end_offset ,
        batch = qt.text ,
        qt.dbid ,
        qt.objectid ,
        s.execution_count ,
        s.total_worker_time ,
        s.total_elapsed_time ,
        s.total_logical_reads ,
        s.total_physical_reads ,
        s.total_logical_writes
FROM    sys.dm_exec_query_stats s
        CROSS APPLY sys.dm_exec_sql_text(s.sql_handle) AS qt
WHERE   s.sql_handle = @sql_handle
AND s.statement_start_offset = @stmtstart AND s.statement_end_offset = @stmtend

You may also like...