I have a function which is generating dynamic T-SQL
statement. The generated code is executed then in a stored procedure.
I want to log some statistics about how long the execution of the generated code is and some IO statistics (logical/physical reads and stuff).
In order to do that, in the function which is building the dynamic T-SQL
statement I append the following line to the final statement:
SET @A = @A + '--' + REPLACE('F2B287FD-1419-48DB-9881-4AA77B99450E', '-', '');
Then I am searching for statistics using the following query:
SELECT *
FROM [sys].[dm_exec_query_stats] QS
CROSS APPLY [sys].[dm_exec_sql_text] (QS.[sql_handle]) ST
WHERE ST.[dbid] = DB_ID()
AND ST.[text] LIKE '%F2B287FD141948DB98814AA77B99450E%';
but it finds nothing.
The code is executed via sp_executesql
procedure. Could anyone tell what's wrong with my query or alternative way of detecting IO
for specific query.
Best Answer
Your problem is caused by the
ST.[dbid] = DB_ID()
in yourWHERE
clause.I've taken a basic example of what I believe you are trying to do from
AdventureWorks
:When you try and get the
dbid
value from thedm_exec_sql_text()
DMV, it's actuallyNULL
for this query, so you are immediately filtering it out.However, by using the
dm_exec_plan_attributes()
DMV,WHERE attribute = 'dbid'
you can get the correct DBID() value for your current database.This is my current go-to query to retrieve this information.