Home Forums SQL Server 2005 T-SQL (SS2K5) Find out if a database is being used and how much RE: Find out if a database is being used and how much

  • Oh yes, thanks. If you CROSS JOIN the sys.dm_exec_query_plan DMF to sys.dm_exec_query_stats you get a dbid. A bit of experimenting reveals that ad hoc plans don't seem to expose a dbid in sys.dm_exec_query_plan if the query is ad hoc as opposed to a stored procedure, but the stored proc query plans do give you a dbid, so this is something to work with.

    So, so far I have the following if anyone is interested:

    WITH last_query_by_db (dbid, Last_query) AS (

    select

    dbid, max(last_execution_time) 'Last_query'

    from

    sys.dm_exec_query_stats

    cross apply

    sys.dm_exec_sql_text(plan_handle)

    group by

    dbid

    )

    select

    d.name, Last_query

    from

    sys.databases d

    left outer join

    last_query_by_db q on q.dbid = d.database_id

    where

    d.name not in ('master','msdb','model','tempdb')

    order by

    1

    I think - but could be wrong - a database that has only ad hoc queries executed against it would appear (incorrectly) from these results to not be used, but i don't suppose this includes too many production systems.

    Bit of a work in progress at the mo!

    Many thanks.

    James