How to get the list of SqlInstances of a particular machine

亡梦爱人 提交于 2019-12-11 06:55:33

问题


Can anyone tell me how to get remote Sqlserver instances using c# and SMO or any api?

I have a remote server name "RemoteMC", which has 2 instances of sql server: "RemoteMc" and "RemoteMC\sqlexpress"

I try to get the instances in code like this:

Server srv=new Server("RemoteMC");
DataTable dt=SmoApplication.EnumAvailableSqlServer(true);

But it returns "Host\sqlexpress"

I don't know what went wrong. How can I get the result back as:

RemoteMC
RemoteMC\sqlexpress;

?


回答1:


The SmoApplication.EnumAvailableSqlServers method is what you're looking for. There are 3 overloads, and one of those takes a string parameter for the server name.

It returns a DataTable whose rows have fields like Version, name, IsLocal, etc.

You'll need to add a reference to the SMO libraries, and you'll probably want to have "using Microsoft.SqlServer.Management.Smo;" at the top of your C# file.

See http://www.sqldbatips.com/showarticle.asp?ID=34 for an intro to SQL SMO.

EDIT: Some code to address this particular problem (I have not compiled or run this):

EDIT:.Rows add to foreach so that it can compile.

DataTable dataTable = SmoApplication.EnumAvailableSqlServers(false);

foreach (DataRow dataRow in dataTable.Rows)
{
    if ((dataRow["Server"] as string) == "MyServerName")
        Console.WriteLine(dataRow["Instance"] as string);
}



回答2:


Use the builtin way.

System.Data.Sql.SqlDataSourceEnumerator



回答3:


One way to do it is to read the registry entry ""Software\Microsoft\Microsoft SQL Server\Instance Names\SQL\" under Local Machine. Are you allowed to read registry in the your solution?



来源:https://stackoverflow.com/questions/1097010/how-to-get-the-list-of-sqlinstances-of-a-particular-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!