Is there a way how to get a list of tables used within an SQL query? Example : I have something like :
SELECT * FROM Table t JOIN OtherTable ON t.id=OtherTab
you can use this sql script right after your query. It will return a list of tables used in the last executed query:
SELECT Field1, Field2
FROM Table t JOIN OtherTable ON t.id=OtherTable.t_id
;WITH vwQueryStats AS(
SELECT
COALESCE(OBJECT_NAME(s2.objectid),'Ad-Hoc') AS ProcName
,execution_count
,s2.objectid
,(
SELECT TOP 1
SUBSTRING(s2.TEXT,statement_start_offset / 2+1
,( ( CASE WHEN statement_end_offset = -1
THEN (LEN(CONVERT(NVARCHAR(MAX),s2.TEXT)) * 2)
ELSE statement_end_offset END)- statement_start_offset) / 2+1)) AS sql_statement
,last_execution_time
FROM sys.dm_exec_query_stats AS s1
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2
)
SELECT TOP 1 *
INTO #lastQueryStats
FROM vwQueryStats x
WHERE sql_statement NOT like 'WITH vwQueryStats AS%'
ORDER BY last_execution_time DESC
SELECT
TABLE_NAME
FROM #lastQueryStats, INFORMATION_SCHEMA.TABLES tab
WHERE CHARINDEX( tab.TABLE_NAME, sql_statement) > 0
DROP TABLE #lastQueryStats
I've taken the query that retrieves the last executed query from this post and I modified it a bit to match with your example.
The output will be as you requested:
Table
OtherTable
Then if you want to have them comma separated you can do:
DECLARE @tableNames VARCHAR(MAX)
SELECT @tableNames = COALESCE(@tableNames + ', ', '') + TABLE_NAME
FROM #lastQueryStats, INFORMATION_SCHEMA.TABLES tab
WHERE CHARINDEX( tab.TABLE_NAME, sql_statement) > 0
SELECT @tableNames
However you should be wary that in a 'usual' production or QA environment with thousands of query executed concurrently this mightn't work as another query could be executed in between your first query and the query that extracts info from db stats.
Hope it helps