如何终止SQL Server会话或会话ID

本文关键字:会话 Server ID SQL 何终止 终止 | 更新日期: 2023-09-27 17:58:26

我正试图使用kill <spid>从C#窗口窗体终止SQL Server 2012中的会话,但当我这样做时,会出现一个错误:

无法使用KILL杀死您自己的进程

代码:

// to do DB backup
private void spid2_Click(object sender, EventArgs e)
{
    string SQLDataBases;
    SQLDataBases = "select @@spid ";
    SQLDataBases += "BACKUP DATABASE School TO DISK = ''C:''Program Files''Microsoft SQL Server''MSSQL11.MSSQLSERVER''MSSQL''Backup''AdventureWorks333.BAK'' ";
    string svr = "Server=" + localsrv + ";Initial Catalog=master;Integrated Security = SSPI;";
    SqlConnection cnBk = new SqlConnection(svr);
    Command = new SqlCommand(SQLDataBases, cnBk);
    Command.CommandText = SQLDataBases;
    SqlDataAdapter da = new SqlDataAdapter(Command);
    DataTable dtDatabases = new DataTable();
    try
    {
        cnBk.Open();
        da.Fill(dtDatabases);
        label1.Text = dtDatabases.Rows[0][0].ToString();
    }
    catch (Exception ex)
    {
        string s = ex.ToString();
        MessageBox.Show(s);
        label1.Text = dtDatabases.Rows[0][0].ToString();
    }
    finally
    {
        if (cnBk.State == ConnectionState.Open)
        {
            cnBk.Close();
            cnBk.Dispose();                   
        }
    }
}
// to kill backup session
private void kill_Click(object sender, EventArgs e)
{
    string SQLRestor;
    SQLRestor = "Use master; kill " + label1.Text;
    string svr = "Server=" + localsrv + ";Initial Catalog=master;Integrated Security = SSPI;";
    SqlConnection cnRestore = new SqlConnection(svr);
    SqlCommand cmdBkUp = new SqlCommand(SQLRestor, cnRestore);
    try
    {
        cnRestore.Open();
        cmdBkUp.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        string s = ex.ToString();
    }
    finally
    {
        if (cnRestore.State == ConnectionState.Open)
        {
            cnRestore.Close();
            cnRestore.Dispose();
        }
    }
}

如何终止SQL Server会话或会话ID

始终对一次性类使用"using"(也用于关闭和处置),从不在查询中连接字符串,始终使用参数化查询以避免sql注入。这是如何使用SqlConnection、SqlDataAdapter和SqlCommand:的示例

  var connectionString = "...";
  var sqlQuery = "...";
  // Sample using SqlCommand
  try
  {
    using (var conn = new SqlConnection(connectionString))
    {
      conn.Open();
      using (var cmd = new SqlCommand(sqlQuery, conn))
      {
        cmd.ExecuteNonQuery();
      }
    }
    MessageBox.Show("OK, SqlConnection and SqlCommand are closed and disposed properly");
  }
  catch (Exception ex)
  {
    MessageBox.Show("Error : " + ex);
  }
  // Sample using SqlDataAdapter
  try
  {
    var dataTable = new DataTable();
    using (var conn = new SqlConnection(connectionString))
    {
      conn.Open();
      using (var sda = new SqlDataAdapter(sqlQuery, conn))
      {
        sda.Fill(dataTable);
      }
    }
    MessageBox.Show("OK, SqlConnection and SqlDataAdapter are closed and disposed properly, use DataTable here...");
  }
  catch (Exception ex)
  {
    MessageBox.Show("Error : " + ex);
  }

"不能使用KILL杀死自己的进程"是有原因的。如果使用完会话,请关闭连接:SqlConnection是一个IDisposable,因此将其封装在using() {}块中会在使用完后自动关闭它。这会将连接句柄返回到池中,由SQL server客户端组件决定是保留它以备后续连接,还是将其丢弃。SQL server在管理其进程生命周期方面做得很好,并杀死它们是一种管理选项,但正常操作中的应用程序不应该做任何事情(除了一些原因,请参阅此处)

也就是说,要回答实际问题:要杀死进程A,您必须打开第二个连接B和KILLA的进程(SPID)。只要"一个SPID=一个连接=一个会话"的假设成立(对于所有当前的SQL server版本都成立),这将起作用。此外,您的用户需要ALTER ANY CONNECTION权限。这通常仅限于sysadmin和processadmin角色,您的应用程序在生产环境中不太可能具有此功能。

参考文献:

http://www.sqlservercentral.com/Forums/Topic1503836-1292-1.aspxhttp://sqlserverplanet.com/dba/spid-what-is-it