【问题标题】:How to list the SQL Server Instances installed on a local machine? ( Only local )如何列出本地计算机上安装的 SQL Server 实例? (仅限本地)
【发布时间】:2011-03-14 15:52:04
【问题描述】:

我想知道是否有办法列出本地计算机上安装的 SQL Server 实例。

SqlDataSourceEnumeratorEnumAvailableSqlServers 不要这样做,因为我不需要本地网络上的实例。

【问题讨论】:

  • 查看我的答案 - EnumAvailableSqlServers 有一个标志 localOnly,您可以将其设置为 true 以仅在本地计算机上查找 SQL Server 实例

标签: c# sql-server


【解决方案1】:

直接访问 Windows 注册表不是 MS 推荐的解决方案,因为它们可以更改键/路径。但我同意 SmoApplication.EnumAvailableSqlServers()SqlDataSourceEnumerator.Instance 无法在 64 位平台上提供实例。

从 Windows 注册表获取数据,请记住 x86x64 平台之间的注册表访问差异。 64 位版本的 Windows 将数据存储在系统注册表的不同部分,并将它们组合成视图。所以使用 RegistryView 是必不可少的。

using Microsoft.Win32;

RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
    RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
    if (instanceKey != null)
    {
        foreach (var instanceName in instanceKey.GetValueNames())
        {
            Console.WriteLine(Environment.MachineName + @"\" + instanceName);
        }
    }
}

如果您在 64 位操作系统上寻找 32 位实例(很奇怪,但可能),您需要查看:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server

【讨论】:

  • 挖了将近 3 个小时后,这对我有用。谢谢。
【解决方案2】:

您可以使用 localOnly = True 调用 EnumAvailableSQlServers

public static DataTable EnumAvailableSqlServers(bool localOnly)

MSDN docs for EnumAvailableSqlServers

【讨论】:

  • 这会为我返回 0 个服务器,但我知道我的计算机上有 3 个实例正在运行
  • 如果只有一个实例,则不显示实例名称。在我的情况下,我只有一个(本地)\SQLEXPRESS 实例,但此函数返回正确的 PC 名称,但实例名称为空。
  • 这不适用于 SQL Server > 2008。如果您有较新版本的 SQL Server,请使用下面的答案。
【解决方案3】:
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
foreach (System.Data.DataRow row in table.Rows)
        {
            if (row["ServerName"] != DBNull.Value && Environment.MachineName.Equals(row["ServerName"].ToString()))
            {
                string item = string.Empty;
                item = row["ServerName"].ToString();
                if(row["InstanceName"] != DBNull.Value ||  !string.IsNullOrEmpty(Convert.ToString(row["InstanceName"]).Trim()))
                {
                    item += @"\" + Convert.ToString(row["InstanceName"]).Trim();
                }
                listview1.Items.Add(item);
            }
        }

【讨论】:

    【解决方案4】:

    您可以使用注册表获取本地系统中的sql server实例名称

    private void LoadRegKey()        
    {            
        RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names");            
        foreach (string sk in key.GetSubKeyNames())            
        {                
          RegistryKey rkey = key.OpenSubKey(sk);                
          foreach (string s in rkey.GetValueNames())                
          {                    
             MessageBox.Show("Sql instance name:"+s);                
          }            
        }        
    }
    

    【讨论】:

      【解决方案5】:

      结合几种方法:

      using Microsoft.SqlServer.Management.Smo;
      using Microsoft.SqlServer.Management.Smo.Wmi;
      using System;
      using System.Collections.Generic;
      using System.Data;
      using System.Diagnostics;
      using System.Linq;
      using Microsoft.Win32;
      
      namespace SqlServerEnumerator
      {
          class Program
          {
              static void Main(string[] args)
              {
                  Dictionary<string, Func<List<string>>> methods = new Dictionary<string, Func<List<string>>>
                  {
                      {"CallSqlBrowser", GetLocalSqlServerInstancesByCallingSqlBrowser},
                      {"CallSqlWmi32", GetLocalSqlServerInstancesByCallingSqlWmi32},
                      {"CallSqlWmi64", GetLocalSqlServerInstancesByCallingSqlWmi64},
                      {"ReadRegInstalledInstances", GetLocalSqlServerInstancesByReadingRegInstalledInstances},
                      {"ReadRegInstanceNames", GetLocalSqlServerInstancesByReadingRegInstanceNames},
                      {"CallSqlCmd", GetLocalSqlServerInstancesByCallingSqlCmd},
                  };
      
                  Dictionary<string, List<string>> dictionary = methods
                      .AsParallel()
                      .ToDictionary(v => v.Key, v => v.Value().OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList());
      
                  foreach (KeyValuePair<string, List<string>> pair in dictionary)
                  {
                      Console.WriteLine(string.Format("~~{0}~~", pair.Key));
                      pair.Value.ForEach(v => Console.WriteLine(" " + v));
                  }
      
                  Console.WriteLine("Press any key to continue.");
                  Console.ReadKey();
              }
      
              private static List<string> GetLocalSqlServerInstancesByCallingSqlBrowser()
              {
                  DataTable dt = SmoApplication.EnumAvailableSqlServers(true);
                  return dt.Rows.Cast<DataRow>()
                      .Select(v => v.Field<string>("Name"))
                      .ToList();
              }
      
              private static List<string> GetLocalSqlServerInstancesByCallingSqlWmi32()
              {
                  return LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use32bit);
              }
      
              private static List<string> GetLocalSqlServerInstancesByCallingSqlWmi64()
              {
                  return LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use64bit);
              }
      
              private static List<string> LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture providerArchitecture)
              {
                  try
                  {
                      ManagedComputer managedComputer32 = new ManagedComputer();
                      managedComputer32.ConnectionSettings.ProviderArchitecture = providerArchitecture;
      
                      const string defaultSqlInstanceName = "MSSQLSERVER";
                      return managedComputer32.ServerInstances.Cast<ServerInstance>()
                          .Select(v =>
                              (string.IsNullOrEmpty(v.Name) || string.Equals(v.Name, defaultSqlInstanceName, StringComparison.OrdinalIgnoreCase)) ?
                                  v.Parent.Name : string.Format("{0}\\{1}", v.Parent.Name, v.Name))
                          .OrderBy(v => v, StringComparer.OrdinalIgnoreCase)
                          .ToList();
                  }
                  catch (SmoException ex)
                  {
                      Console.WriteLine(ex.Message);
                      return new List<string>();
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex);
                      return new List<string>();
                  }
              }
      
              private static List<string> GetLocalSqlServerInstancesByReadingRegInstalledInstances()
              {
                  try
                  {
                      // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\InstalledInstances
                      string[] instances = null;
                      using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"))
                      {
                          if (rk != null)
                          {
                              instances = (string[])rk.GetValue("InstalledInstances");
                          }
      
                          instances = instances ?? new string[] { };
                      }
      
                      return GetLocalSqlServerInstances(instances);
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex);
                      return new List<string>();
                  }
              }
      
              private static List<string> GetLocalSqlServerInstancesByReadingRegInstanceNames()
              {
                  try
                  {
                      // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL
                      string[] instances = null;
                      using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"))
                      {
                          if (rk != null)
                          {
                              instances = rk.GetValueNames();
                          }
      
                          instances = instances ?? new string[] { };
                      }
      
                      return GetLocalSqlServerInstances(instances);
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex);
                      return new List<string>();
                  }
              }
      
              private static List<string> GetLocalSqlServerInstances(string[] instanceNames)
              {
                  string machineName = Environment.MachineName;
      
                  const string defaultSqlInstanceName = "MSSQLSERVER";
                  return instanceNames
                      .Select(v =>
                          (string.IsNullOrEmpty(v) || string.Equals(v, defaultSqlInstanceName, StringComparison.OrdinalIgnoreCase)) ?
                              machineName : string.Format("{0}\\{1}", machineName, v))
                      .ToList();
              }
      
              private static List<string> GetLocalSqlServerInstancesByCallingSqlCmd()
              {
                  try
                  {
                      // SQLCMD -L
                      int exitCode;
                      string output;
                      CaptureConsoleAppOutput("SQLCMD.exe", "-L", 200, out exitCode, out output);
      
                      if (exitCode == 0)
                      {
                          string machineName = Environment.MachineName;
      
                          return output.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)
                              .Select(v => v.Trim())
                              .Where(v => !string.IsNullOrEmpty(v))
                              .Where(v => string.Equals(v, "(local)", StringComparison.Ordinal) || v.StartsWith(machineName, StringComparison.OrdinalIgnoreCase))
                              .Select(v => string.Equals(v, "(local)", StringComparison.Ordinal) ? machineName : v)
                              .Distinct(StringComparer.OrdinalIgnoreCase)
                              .ToList();
                      }
      
                      return new List<string>();
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex);
                      return new List<string>();
                  }
              }
      
              private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
              {
                  using (Process process = new Process())
                  {
                      process.StartInfo.FileName = exeName;
                      process.StartInfo.Arguments = arguments;
                      process.StartInfo.UseShellExecute = false;
                      process.StartInfo.RedirectStandardOutput = true;
                      process.StartInfo.CreateNoWindow = true;
                      process.Start();
      
                      output = process.StandardOutput.ReadToEnd();
      
                      bool exited = process.WaitForExit(timeoutMilliseconds);
                      if (exited)
                      {
                          exitCode = process.ExitCode;
                      }
                      else
                      {
                          exitCode = -1;
                      }
                  }
              }
          }
      }
      

      【讨论】:

        【解决方案6】:
         public static string SetServer()
            {
                string serverName = @".\SQLEXPRESS";
                var serverNameList = SqlHelper.ListLocalSqlInstances();
                if (serverNameList != null)
                {
                    foreach (var item in serverNameList)
                        serverName = @"" + item;
                }
                return serverName;
            }
        

        获取本地服务器名称

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多