Question

Is it possible from with in a CLR function that is being executed by SQL to determine the SQL statement that invoked the CLR function in the first place. If there is no direct way, what about an indirect way like getting some kind of handle identifier and going back and querying SQL or it's logs for that info?

Example:

SQL executes:

select * from genericTable1 join genericCLRfunction() f on genericTable1.col = f.col;

and within the CLR invoked by the SQL statement calling genericCLRfunction() I would like to end up with a string equal to:

"select * from genericTable1 join genericCLRfunction() f on genericTable1.col = f.col;"

Was it helpful?

Solution

I can't actually try this right now, but here is a possibility. You can get the session id in your CLR like so...

using (SqlConnection cn = new SqlConnection("context connection=true;"))
{
   cn.Open();
   SqlCommand cmd = new SqlCommand("SELECT @@SPID", cn);
   int spid = Convert.ToInt32(cmd.ExecuteScalar());
   cn.Close();
}

Then, try to use the query shown in the accepted answer for this SO question...

List the queries running on SQL Server

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top