Question

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.

  • I'm running the Activity Monitor and the DMV query under the same login
  • That login is the owner of the OpenLink database
  • If I run select * from fn_my_permissions (NULL, 'server'); then I can see I have VIEW SERVER STATE permissions
  • If I remove the where clause, I see entries for other databases such as msdb and distribution
  • Here is a screenshot of the mappings for my login. I'm pretty sure I shouldn't be the owner, but that's a different question.

Screenshot of SQL Server permissions showing db_owner role membership

Can anyone tell me why my DMV query is returning zero rows for this database?

Was it helpful?

Solution

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'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top