Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: SS7,VB5,VB6
Expertise: Intermediate
Apr 29, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 service
Dim SQLServer As New SQLDMO.SQLServer

' starting the service requires that you specify 
' the server's name and user credentials
SQLServer.Start False, "MyServer", "sa", "mypwd"

' pausing, continuing and stopping the service
' doesn't require any additional argument
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
Francesco Balena
Thanks for your registration, follow us on our social networks to keep up-to-date