I'm trying to create a SQL CLR stored procedure that will create a table, pass the table name onto a service which will bulk insert some data into it, display the results of the table, then clean up the table.
What I've tried so far:
Use
SqlTransaction. Cancelling the transaction works, but it puts my query window into a state where I couldn't continue working on it.The transaction active in this session has been committed or aborted by another session
Use
TransactionScope. Same issue as 1.Manually clean up the table in a
finallyclause by issuing aDROP TABLESqlCommand. This doesn't seem to get run, though mySqlContext.Pipe.Send()prior to issuing the command does. It doesn't seem like it's related to any time constraints since if I issue aThread.Sleep(2000)before printing another line, it still prints the second line whereas thecommand.ExecuteNonQuery()would stop before printing the second line.Placing the manual cleanup code into a CER or
SafeHandle. This doesn't work as having a CER requires some guarantees, including not allocating additional memory or calling methods that are not decorated with aReliabilityContract.
Am I missing something obvious here? How do I handle the user cancelling their query?
Edit: There were multiple iterations of the code for each scenario, but the general actions taken are along the lines of the following:
[SqlProcedure]
public static void GetData(SqlString code)
{
Guid guid = Guid.NewGuid();
using (var connection = new SqlConnection("context connection=true"))
{
connection.Open();
try
{
SqlContext.Pipe?.Send("Constrain");
SqlCommand command1 = new SqlCommand($"CREATE TABLE qb.{code}_{guid:N} (Id INT)", connection);
command1.ExecuteNonQuery();
SqlContext.Pipe?.Send($"Create: qb.{code}_{guid:N}");
//emulate service call
Thread.Sleep(TimeSpan.FromSeconds(10));
SqlContext.Pipe?.Send($"Done: qb.{code}_{guid:N}");
}
finally
{
SqlContext.Pipe?.Send("1");
//drop table here instead of sleep
Thread.Sleep(2000);
SqlContext.Pipe?.Send("2");
}
}
}
finallyblock does not executeDROP TABLEas mentioned in attempt 3.EXEC clrproc 'parameter'