简体   繁体   中英

Detecting if SQL server is running

I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive.

Any ideas?

Well, the brute force solution is to attempt to initiate a connection with the database on each server. That will tell you whether it's running, though you could have timeout issues.

The more elegant (but more difficult... isn't that always the way?) solution would be to use WMI to connect to the remote machine and find out if the SQL server process is running.

System.Data.Sql.SqlDataSourceEnumerator will return all instances of SQL Server currently running.
MSDN Link

Use the TCPClient Class to create a generic function that connects in TCP to a given IP address.

Then iterate over the list of servers you want to test and try to open a connection to port 1433.

If you need specific servers, use WMI. If you just want all available servers:

http://support.microsoft.com/kb/q287737/

SqlDataSourceEnumerator gives you all instances but they are not necessarily running. For local instances of SQL, you can use ServiceController object, namespace System.ServiceProcess. Service name is concatination of "MSSQL$" and "InstanceName" from SqlDataSourceEnumerator. Set ServiceName property of the ServiceController object, and you can check "Status" property - Stopped, Running, Pended etc. Hence, you can filter "Running" ones

I would certainly go with Vincent's answer. Just make absolutely certain you are closing and disposing the tcp connections properly etc. WMI seems a bit of overkill to me if that is all you're after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM