Find All Queries executed on a particular Table

Leave a comment (0) Go to comments

Question :

what all select queries are running against a particular table ?

SQL queries used to refer data for a particular table ?

Solution : This following script will show you all the queries that have run against a particular table since the last time SQL Server was started.

SELECT DISTINCT TOP 500

ProcedureName = OBJECT_SCHEMA_NAME(sqt.objectid) + '.' + OBJECT_NAME(sqt.objectid)


,SQLStatement = SUBSTRING(

                sqt.Text

                ,(qs.statement_start_offset/2)+1

                ,CASE qs.statement_end_offset

                WHEN -1 THEN DATALENGTH(sqt.text)

                ELSE qs.statement_end_offset

                END - (qs.statement_start_offset/2) + 1

                )

,DiskReads = qs.total_physical_reads   -- The worst reads, disk reads

,MemoryReads= qs.total_logical_reads    --Logical Reads are memory reads

,ExecutionCount = qs.execution_count

,CPUTime = qs.total_worker_time

,DiskWaitAndCPUTime = qs.total_elapsed_time

,MemoryWrites  = qs.max_logical_writes

,DateCached    = qs.creation_time

,DatabaseName  = DB_Name(sqt.dbid)

,LastExecutionTime  = qs.last_execution_time

,sre.*

FROM sys.dm_exec_query_stats AS qs

CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS sqt

CROSS APPLY sys.dm_sql_referenced_entities(

OBJECT_SCHEMA_NAME(sqt.objectid) + '.' + OBJECT_NAME(sqt.objectid)

        , 'OBJECT'

    ) sre

WHERE sqt.dbid = db_id() -- Filter by current database id

AND sre.referenced_schema_name + '.' + sre.referenced_entity_name = 'dbo.UnSparsed'

This query can also be useful, where DBA are not not involved at application level we need to find out what all SQL queries are running against a particular table or when we defining indexes, we wanted to know what all select queries are running against a particular table.

Note : DMV [sys.dm_sql_referenced_entities] is new DMV, which introduced in SQL Server 2008, thus this query will not work in SQL Server 2005. Approx 46 new DMVs are newly added in SQL Server 2008.

EOF - Find All Queries executed on a particular Table, SQL Server 2012 , 2008 R2 , 2008 , 2005 , 2000

Leave a Reply

Your email address will not be published. Required fields are marked *


*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.