smo.application.enumAvailableSqlServers未返回可用的SQL Server

时间:2014-07-28 17:46:54

标签: c# sql smo

我正在尝试使用以下c#代码在列表框中显示可用的sql服务器:

DataTable dt = SmoApplication.EnumAvailableSqlServers(false);

foreach (DataRow dr in dt.Rows)
{
   listBox3.Items.Add(dr["Name"].ToString());
}

但是,列表框仍为空,当我调试时,我发现dt.Rows等于零,虽然我有一台带有SQL Server 2012 Express的服务器。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

一种可能性是您没有SQL Server Browser Service正在运行。根据MSDN页面:

  

SQL Server Browser有助于执行以下操作:

     
      
  • 浏览可用服务器列表
  •   
  • 连接到正确的服务器实例
  •   
  • 连接到专用管理员连接(DAC)端点
  •   

我在32位应用程序中要求提供本地SQL实例列表并且由于计算机上只有64位实例而空出来的另一件事就是关注注册表:< / p>

 List<string> servers = new List<string>();

 // Get servers from the registry (if any)
 RegistryKey key = RegistryKey.OpenBaseKey(
   Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
 key = key.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
 object installedInstances = null;
 if (key != null) { installedInstances = key.GetValue("InstalledInstances"); }
 List<string> instances = null;
 if (installedInstances != null) { instances = ((string[])installedInstances).ToList(); }
 if (System.Environment.Is64BitOperatingSystem) {
    /* The above registry check gets routed to the syswow portion of 
     * the registry because we're running in a 32-bit app. Need 
     * to get the 64-bit registry value(s) */
    key = RegistryKey.OpenBaseKey(
            Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
    key = key.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
    installedInstances = null;
    if (key != null) { installedInstances = key.GetValue("InstalledInstances"); }
    string[] moreInstances = null;
    if (installedInstances != null) { 
       moreInstances = (string[])installedInstances;
       if (instances == null) {
          instances = moreInstances.ToList();
       } else {
          instances.AddRange(moreInstances);
       }
    }
 }
 foreach (string item in instances) {
    string name = System.Environment.MachineName;
    if (item != "MSSQLSERVER") { name += @"\" + item; }
    if (!servers.Contains(name.ToUpper())) { servers.Add(name.ToUpper()); }
 }