Programmatically start and stop SQL Server main service

Programmatically start and stop SQL Server main service

Using the SQL-DMO object model you can programmatically start, stop, pause, and continue the main SQL Server service. In the following code snippet the server is “MyServer”, and “sa” / “mypwd” is the user name and password of a user that is allowed to start/stop the service:

' NOTE: this code assumes that you've added a reference to the'       SQL-DMO type library in the References dialog box' start, pause, continue and stop SQL Server serviceDim SQLServer As New SQLDMO.SQLServer' starting the service requires that you specify ' the server's name and user credentialsSQLServer.Start False, "MyServer", "sa", "mypwd"' pausing, continuing and stopping the service' doesn't require any additional argumentSQLServer.PauseSQLServer.ContinueSQLServer.Stop

You can also test the current state of the SQL Server service by means of the Status property:

' show current state of the service Select Case SQLServer.Status    Case SQLDMOSvc_Paused: lblStatus = "Paused"    Case SQLDMOSvc_Running: lblStatus = "Running"    Case SQLDMOSvc_Starting: lblStatus = "Starting"    Case SQLDMOSvc_Stopped: lblStatus = "Stopped"End Select

Finally, you can programmatically enable or disable the autostart feature (that is, the capability to run the SQL Server service automatically when the system reboots):

SQLServer.Registry.AutostartServer = True     ' autostart SQL Server

See also  Redefining Energy Management: Advanced Solutions for Modern Buildings

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist