How to list available instances of SQL Servers using SMO in C#?

雨燕双飞 提交于 2019-11-26 11:38:31

问题


Can anybody explain me what I wrong I am doing in the following piece of code:

DataTable dt=SmoApplication.EnumAvailableSqlServer(true);
Server sr = new Server(\"Test\");

foreach(DataBase db in sr.DataBases)
{
    Console.WriteLine(db[\"name\"]);
}

It gives an exception in sr.Databases that can not be connected.


回答1:


Take a look at the following links they may be helpful:

  • Enumerate SQL Server Instances in C#, Using ODBC
  • How to get a list of available SQL Servers using C# (MSDN)
  • Populating a list of SQL Servers

Alternatively you could change your code to this:

DataTable dt = SmoApplication.EnumAvailableSqlServers(false);
if (dt.Rows.Count > 0)
{
    foreach (DataRow dr in dt.Rows)
    {
        Console.WriteLine(dr["Name"]);
    }
}

Hope this solves your problem.




回答2:


Do you have a SQL Server with the instance name Test? If not, that is your problem.

It looks like you are trying to enumerate all of the local SQL Server instances. If so, this code will work:

DataTable dt = SmoApplication.EnumAvailableSqlServers(true);

foreach (DataRow dr in dt.Rows)
{
    Console.WriteLine(dr["Name"]);
    Console.WriteLine("   " + dr["Server"]);
    Console.WriteLine("   " + dr["Instance"]);
    Console.WriteLine("   " + dr["Version"]);
    Console.WriteLine("   " + dr["IsLocal"]);
}



回答3:


Just in case the question is titled wrong i.e. he wants to find the databases in the particular instance:

using System;
using Microsoft.SqlServer.Management.Smo;
using System.Data;
using System.Windows.Forms;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Server sr = new Server("MACHINE_NAME\\INSTANCE_NAME");

            try
            {
                foreach (Database db in sr.Databases)
                {
                    Console.WriteLine(db.Name);
                }
                Console.Read();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
            }
        }
    }
}

Else Lucas Aardvark answer is most appropriate.




回答4:


using Microsoft.Win32;

       RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
        String[] instances = (String[])rk.GetValue("InstalledInstances");
        if (instances.Length > 0)
        {
            foreach (String element in instances)
            {
               Console.WriteLine(element);    // element is your server name                
            }
        }


来源:https://stackoverflow.com/questions/1130580/how-to-list-available-instances-of-sql-servers-using-smo-in-c

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