This is something I am just interested in knowing if it is possible.
Could I write an SQL query that could return the text of itself as a variable?
Where I might use this would be on things like reports that I might want to return a variable that saves the actual query that ran to generate the report, or as a debugging tool.
I have seen there is:
sys.dm_exec_text_query_plan
that would return the text of the query but can't see an easy way to always get the currently executing queries ID to link back to this table.
Has anyone ever written something to do something like this?
I am using SQL Server 2008, 2012 and 2014.
Best Answer
There is no way that a query can output its own text, that I am aware of, but you can certainly capture it using sys.dm_exec_requests.
You can try this:
Or inside SP:
I think you would be better served by SQL Trace though.
For a procedure, you can use sp_helptext and equivalents to get its text. I don't think you would need to capture SP text at the point execution as SPs don't get redefined often. Capturing SP name should be enough.