views:

839

answers:

3

Let's say you have execute the following (long running) process from your code:

int processID = DB.Execute(SQL); //some long running sql statement

Is there a way to programatically call SQL Server to cancel the process if it is taking too long (kind of like hitting the "Stop" button in QueryAnalyzer)?

//cancel the process if it is taking too long
DB.Execute("sp_CancelProcess @ProcessID=" + processID);
+3  A: 

Kill @Spid

note that this is a last effort. you should just close the connection on the client to kill the process.

Mladen Prajdic
Just be aware that you can't kill your own spid, you need to create another connection and then kill the spid from the
SQLMenace
+2  A: 

use Kill with the process id

Just be aware that you can't kill your own spid, you need to create another connection and then kill the spid from the

if you try to kill your own SPID you will get the following error

Server: Msg 6104, Level 16, State 1, Line 1 Cannot use KILL to kill your own process.

SQLMenace
A: 

You have to run your query asynchronously, as follows:

    SqlConnection _anotherConnection;
    SqlCommand _anotherCommand;
    IAsyncResult _anotherCommandStarted;
    _anotherCommand = _anotherConnection.CreateCommand();
    _anotherCommand.CommandText = string.Format("SET DEADLOCK_PRIORITY HIGH; BEGIN TRANSACTION; {0};", hookCommand);
    _anotherCommand.CommandType = CommandType.Text;
    _anotherCommand.ExecuteNonQuery();
    _anotherCommand.CommandText = "UPDATE Data.Hook1 SET i=1-i";
    _anotherCommandStarted = _anotherCommand.BeginExecuteNonQuery();

To cancel the command, run this:

    _anotherCommand.EndExecuteNonQuery(_anotherCommandStarted);
AlexKuznetsov
The BeginExecuteNonQuery() suggestion is good, but EndExecuteNonQuery does not cancel the command - it blocks until the command completes.
Mike