2009-07-07 66 views
6

比方说,你必须从你的代码执行以下(长时间运行)过程:你怎么能取消的SQL Server执行过程编程

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

有没有一种方法以编程方式调用SQL Server来取消的话进程它需要很长时间(有点像在QueryAnalyzer中点击“停止”按钮)?

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

请多关注您的标签选择 - 标签是您如何将您的问题与适当的受众连接起来的方式。 – 2009-07-07 14:04:45

回答

4

Kill @Spid

注意,这是最后的努力。你应该关闭客户端上的连接来终止进程。

+0

只要知道你不能杀死你自己的spid,你需要创建另一个连接,然后从 – SQLMenace 2009-07-07 14:09:16

5

使用KILL进程ID:

KILL 53; 

要知道,你不能终止自己的spid,您需要创建另一个连接,然后杀死从

的SPID如果您试图杀死自己的SPID您将收到以下错误

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

你必须异步运行您的查询,如下所示:

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(); 

要取消命令,运行此:

_anotherCommand.EndExecuteNonQuery(_anotherCommandStarted); 
+1

杀死spid BeginExecuteNonQuery()建议是好的,但EndExecuteNonQuery不会取消该命令 - 它会阻塞,直到命令完成。 – Mike 2009-11-13 16:33:15

0
sp_who2 

进程列表显示

Find you SPID 

Kill SPID 

如果错误信息不能杀自己的进程

看看您的管理工作室中的流程在哪里停止并停止。

或关闭当前连接并重新打开并尝试立即终止。