【问题标题】:smo.application.enumAvailableSqlServers not returning available SQL Serverssmo.application.enumAvailableSqlServers 不返回可用的 SQL Server
【发布时间】:2014-07-28 17:46:53
【问题描述】:

我正在尝试使用以下 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 的服务器。

有什么想法吗?

【问题讨论】:

  • 相关阅读:sqlblogcasts.com/blogs/jonsayce/archive/2008/02/10/… 另外,您需要保持一致——您在上一个问题(建议您使用 SMO)中声称使用 SQLEXPRESS 2010。它是什么?
  • 是的,很抱歉造成混乱,现在是 2012 年。
  • 不,没有例外。它执行代码,但从不进入 foreach 语句。
  • 罗杰,说“它永远不会进入 for 循环”是没有意义的。除非该 smo 调用使您的应用程序立即退出,否则肯定存在异常。这很可能是导致退出的异常!当您单步执行调试器时会发生什么? smo 电话会返回吗?

标签: c# sql smo


【解决方案1】:

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

SQL Server Browser 有助于以下操作:

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

在一个 32 位应用程序请求本地 SQL 实例列表但由于机器上只有 64 位实例而出现空白的情况下,我所做的另一件事是探索注册表:

 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()); }
 }

【讨论】:

  • Server 2008 和 Windows 8 的正确键名是“Instance Names”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
  • 2017-11-03
  • 2018-10-28
  • 1970-01-01
  • 2014-07-22
相关资源
最近更新 更多