I am trying to query the DMVs in SQL Server 2008 R2.
On this server are two user databases called histrx and OpenLink. To prove I have their names correct:
select db_id('histrx') -- Returns 5
select db_id('OpenLink') -- Returns 7
If I run the following query, picking out entries for the histrx database, I get 25 rows in the result set:
select top 25
total_worker_time/execution_count as avg_worker_time,
total_logical_reads/execution_count as avg_logical_reads,
db_name(s.dbid) as [db_name],
object_name(s.objectid, s.dbid) as [object_name],
execution_count,
plan_generation_num,
last_execution_time,
creation_time,
[text],
p.query_plan
from
sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) s
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) p
where
db_name(s.dbid) = 'histrx'
order by
avg_logical_reads desc
If I then change the where
clause to the following, no rows are returned:
where
db_name(s.dbid) = 'OpenLink'
I know that there is a significant amount of activity on the OpenLink database. If I look at Recent Expensive Queries in the Activity Monitor, I can see entries for OpenLink, and I'm pretty sure this is using the DMVs underneath.
select * from fn_my_permissions (NULL, 'server');
then I can see I have VIEW SERVER STATE permissionswhere
clause, I see entries for other databases such as msdb and distributionCan anyone tell me why my DMV query is returning zero rows for this database?
Quote from Books Online 2008 R2 > sys.dm_exec_sql_text:
dbid smallint ID of database. Is NULL for ad hoc and prepared SQL statements.
1) So, for this type of SQL statements, where db_name(s.dbid) = 'OpenLink'
means where NULL = 'OpenLink'
and this predicate is evaluated to UNKNOWN
.
2) dbid
column is NOT NULL
for "non-adhoc and non-prepared SQL" statements (ex. for stored procedures).
3) For SQL 2008R2 you might get the dbid
for "ad hoc and prepared SQL statements" from sys.dm_exec_plan_attributes ( plan_handle )
function (link) using this query:
SELECT
...
ISNULL(src.dbid,CONVERT(SMALLINT,att.value)) AS my_dbid,
DB_NAME(ISNULL(src.dbid,CONVERT(SMALLINT,att.value))) my_dbname,
...
FROM
sys.dm_exec_query_stats qs
...
CROSS APPLY sys.dm_exec_plan_attributes(qs.plan_handle) att
WHERE att.attribute='dbid'