tags:

views:

131

answers:

5

How can I use C# to stop SQL Server?

+2  A: 

Try stopping the service.

using System.ServiceProcess;

...

ServiceController controller  = new ServiceController();

controller.MachineName = ".";
controller.ServiceName = "MySqlServerInstance";


controller.Stop();
Wix
+10  A: 

From http://www.csharp-examples.net/restart-windows-service/

public static void StopService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
  }
  catch
  {
    // ...
  }
}
RedFilter
+1 - this has the advantage that you know whether it worked or not, and when
Steve Townsend
+3  A: 

Have you tried

Process.Start("net stop mssqlserver")
adam straughan
A: 
using System.Diagnostics;

public static bool StopProcess(string name)
{
    try
    {
        var process = Process.GetProcesses().SingleOrDefault(p => p.ProcessName == name);
        process.WaitForExit(); 
        return true;
    }
    catch (Exception)
    {
        //throw;
        return false;
    }
}
sshow
I would think unexpected `Kill` is not a great idea for SQL Server integrity. Are you sure you would do it this way?
Steve Townsend
@SteveTownsend I did not think of that. You're right
sshow
@Steve Townsend: if TerminateProcess triggered data corruption SQL Server would be out of business. This is why (almost) all RDBMSs use WAL: http://msdn.microsoft.com/en-us/library/ms186259.aspx Torn page protection additionally protects against power outages: http://msdn.microsoft.com/en-us/library/aa337560.aspx
Remus Rusanu
@Remus, you are right but I still would not choose this method when clean service stop is available
Steve Townsend
@SteveTownsend it has been edited to use `WaitForExit()`. I guess that should be a more pleasant halt.
sshow
SingleOrDefault not found in c# ! is t require another using ?
salamonti
`using System.Linq`
sshow
+4  A: 

Execute from a SqlCommand: SHUTDOWN WITH NOWAIT;. The advantages over the other proposed solutions:

  • this requires DB priviledges (sysadmin/serveradmin), not OS privileges
  • works over any network firewall as long as T-SQL is let in (no extra ports needed)
  • you don't need to figure out the service name (MSSQL$instancename)
  • works if the service is started from console (sqlservr -c, not service start)
Remus Rusanu