Aim: Calling a very slow stored procedure (with parameters) asynchronously from code behind of an asp.net web page via single function call, and then forgetting about it.
Notes: I tried using SqlCommand.BeginExecuteNonQuery without calling SqlCommand.EndExecuteNonQuery (see the code below), but the stored procedure didn’t run. (I used a tiny stored procedure to update single field on a table for testing but the field was not updated. It gets update when I use SqlCommand.ExecuteNonQuery).
I am not interested in and don’t know when the stored procedure will end. (So I can’t wait for it to finish to call SqlCommand.EndExecuteNonQuery.)
Situation:
After some research, I found out that sql jobs can be used for this purpose. And for the sp parameters; I can store them in a table and then sp can read them. However I don’t know if this is the right approach to my problem (I am new to SQL world). I hope you can comment on usage of an sql job for this purpose, or suggest alternatives. Thanks.
Code:
using (SqlConnection connection = new SqlConnection(
@"Data Source=XXX\MSSQL2008R2;Initial Catalog=YYY;Integrated Security=True"
+ ";Asynchronous Processing=true"))
{
connection.Open();
SqlCommand cmd = new SqlCommand("spTestProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@pText", DateTime.Now.ToString()));
cmd.BeginExecuteNonQuery(); //Doesn't work.
//cmd.ExecuteNonQuery(); // This works.
}
I was looking for a way of doing this from the code behind of asp.net, but realized there is no easy way of doing it (I didn’t want to think about connection or time out problems). I ended up doing it via a web service.
SqlCommand.BeginexecuteNonQuery(AsyncCallback, Object).Hence my web page keeps working the way I want: Fire the request once, then forget about it.