How to: Stop and Restart the Microsoft SQL Server Service to the Instance of SQL Server in Visual Basic .NET
This section describes how to stop and start the Microsoft SQL Server service by using the ManagedComputer object.
The code example shows how to stop and start services using the SMO ManagedComputer object, which provides an interface to the WMI Provider for Configuration Management.
Stopping and Restarting Microsoft SQL Server service
Start Visual Studio 2005.
From the File menu, select New Project. The New Project dialog box appears.
In the Project Types pane, select Visual Basic. In the Templates pane, select Console Application.
(Optional) In the Name box, enter the name of the new application.
Click OK to load the Visual Basic console application template.
On the Project menu, select Add Reference item. The Add Reference dialog box appears. Select Browse and locate the SMO assemblies in the C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies folder. Select the following files:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SqlEnum.dll
Microsoft.SqlServer.SmoEnum.dll
Microsoft.SqlServer.Smo.WmiEnum
On the View menu, click Code.-Or-Select the Module1.vb window to display the code window.
In the code, before any declarations, type the following Imports statements to qualify the types in the SMO namespace.
Imports Microsoft.SqlServer.Management.Smo Imports Microsoft.SqlServer.Management.Smo.Wmi Imports Microsoft.SqlServer.Management.Common
Insert the code that follows this procedure into the main program.
Run and build the application.
Ejemplo
'Declare and create an instance of the ManagedComputer object that represents the WMI Provider services.
Dim mc As ManagedComputer
mc = New ManagedComputer()
'Iterate through each service registered with the WMI Provider.
Dim svc As Service
For Each svc In mc.Services
Console.WriteLine(svc.Name)
Next
'Reference the Microsoft SQL Server service.
svc = mc.Services("MSSQLSERVER")
'Stop the service if it is running and report on the status continuously until it has stopped.
If svc.ServiceState = ServiceState.Running Then
svc.Stop()
Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState))
Do Until String.Format("{0}", svc.ServiceState) = "Stopped"
Console.WriteLine(String.Format("{0}", svc.ServiceState))
svc.Refresh()
Loop
Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState))
'Start the service and report on the status continuously until it has started.
svc.Start()
Do Until String.Format("{0}", svc.ServiceState) = "Running"
Console.WriteLine(String.Format("{0}", svc.ServiceState))
svc.Refresh()
Loop
Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState))
Else
Console.WriteLine("SQL Server service is not running.")
End If
Vea también
Conceptos
Managing Services and Network Settings by Using WMI Provider