Show text from sql_handle

Published 04 October 07 03:50 AM | SQL Master 

Based upon the query or stored procedure execution the plan will be stored in the cache, but it may not be in readable format as it is stored in Hexadecimal when you simply query SYSPROCESSES table. So in order to extract the query plan that is in cache, you can retrieve the SQL text of the query and the query execution plan in XML showplan format at any time.

Using the DMV sys.dm_exec_sql_text you can obtain the XML showplan and to obtain query paln you can use another DMV sys.dm_exec_query_plan dynamic management as follows:

select
(select text from sys.dm_exec_sql_text(put_sql_handle_here)) as sql_text
,(select query_plan from sys.dm_exec_query_plan(put_plan_handle_here)) as query_plan
go

Further to this Books online has another example to get average CPU time with top 5 queries:
SELECT TOP 5 total_worker_time/execution_count AS [Avg CPU Time],
    SUBSTRING(st.text, (qs.statement_start_offset/2)+1, 
        ((CASE qs.statement_end_offset
          WHEN -1 THEN DATALENGTH(st.text)
         ELSE qs.statement_end_offset
         END - qs.statement_start_offset)/2) + 1) AS statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY total_worker_time/execution_count DESC;

 

Comments

# Other SQL Server Blogs around the Web said on October 4, 2007 3:52 AM:

Based upon the query or stored procedure execution the plan will be stored in the cache, but it may not

# SSQA.net - SqlServer-QA.net said on October 4, 2007 4:24 AM:

Based upon the query or stored procedure execution the plan will be stored in the cache, but it may not

Anonymous comments are disabled

About SQL Master

**__________________________________** SQL Server MVP, Sr. DBA & industry expert. - Knowledge is of two kinds. We know a subject ourselves or we know where we can find information on it. It is also a power and you will gain by sharing it.