Control SQL Agent Service using xp_ServiceControl SQL Server Undocumented Stored Procedure
SQL Server administrators (DBAs) and sql programmers can manage services on a SQL Server instance using sql tools like Windows Services Management Console, SQL Server Mamangement Studio and using unsupported T-SQL procedure xp_ServiceControl within sql scripts.
In short, xp_ServiceControl undocumented stored procedure enables sql developers and SQL Server professionals take control of the Windows services running on the SQL Server instance.
As you will see in the xp_servicecontrol syntax, the extended stored procedure xp_servicecontrol takes two arguments.
The first argument identifies the action. The action can be QueryState to query the service status, Start to start SQL service, Stop to stop SQL service.
The second argument identifies the Windows service (or SQL Server service) to control.
The t-sql code to start SQL Server Agent service is as follows :
The sql command to stop Microsoft SQL Server SQL Browser service is as follows :
It is possible to get the following error messages using xp_ServiceControl procedure.
Msg 22003, Level 16, State 1, Line 0
StartService() returned error 1056, 'An instance of the service is already running.'
OR
Msg 22003, Level 16, State 1, Line 0
StartService() returned error 1062, 'The service has not been started.'
OR
Msg 22003, Level 16, State 1, Line 0
StartService() returned error 1051, 'A stop control has been sent to a service that other running services are dependent on.'
SQL Server administrators and t-sql developers can query the status of SQL Server services using xp_servicecontrol with QueryState parameter.
Here is a T-SQL xp_servicecontrol stored procedure sample which controls the SQL Server Agent Service status to see if SQL Agent service is running or stopped.
If the SQL Agent service is just starting, the Current Service State column will display "Starting."
If the SQL Agent service has started and running for a while, the Current Service State value will be displayed as "Running."
If SQL Server Agent has been stopped and is not running currently, the Current Service State value will be "Stopped."
As last note, xp_ServiceControl stored procedure can be used not only to control sql services but also to control Windows services as well just like a sql tool.