简体   繁体   中英

How to kill a SQL Server session or session ID

I'm trying to kill a session in SQL Server 2012 from C# windows Form using kill <spid> but what happens is that when I do that, an error appears:

Cannot use KILL to kill your own process

Code:

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

Always use "using" for disposable classes (also to close and dispose), never concatenate string in query , use always parameterized query to avoid sql injection. This is sample how to use SqlConnection, SqlDataAdapter, and 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);
  }

The "Cannot use KILL to kill your own process" is there for a reason. If you're finished using your session, close the connection: SqlConnection is an IDisposable , so wrapping it in an using() {} block will close it automatically when you're done using it. This will return the connection handle back to the pool, and it is up to the SQL server client components to decide whether to keep it around for follow-up connections, or dispose it. SQL server does a good job of managing its process lifecycle and killing them is an administrative option, but nothing that an application in normal operation should do (except for a few reasons, see here )

That said, to answer the actual question: to kill process A, you'd have to open a second connection B and KILL A's process (SPID). This will work as long as the assumption "one SPID = one connection = one session" holds (true for all current SQL server versions). Furthermore, your user needs the ALTER ANY CONNECTION privilege. This is usually limited to sysadmin and processadmin roles, and your application is unlikely to have this in a production environment.

References:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM