How do I find an already installed name and version of an instance of SQL Server 2014?

I use the code below to get all instance names and server names on my local machine.

private List<string> GetInstanceName()
    {
        var result = new List<String>();
        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())
                {
                    if (!string.IsNullOrEmpty(instanceName))
                    {
                        result.Add(instanceName);
                    }
                }
            }
        }
        return result;
    }

But I also need to get the version. I do not know how to get the version for each instance.

+4
source share
2 answers

With the information obtained from the registry key values ​​in "Instance Names \ SQL", you need to go back to the registry and get the information you are looking for.

Try this code:

// find the installed SQL Server instance names
RegistryKey key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL");

// loop over those instances
foreach (string sqlInstance in key.GetValueNames())
{
    Console.WriteLine("SQL Server instance: {0}", sqlInstance);

    // find the SQL Server internal name for the instance
    string internalName = key.GetValue(sqlInstance).ToString();
    Console.WriteLine("\tInternal instance name: {0}", internalName);

    // using that internal name - find the "Setup" node in the registry
    string instanceSetupNode = string.Format(@"SOFTWARE\Microsoft\Microsoft SQL Server\{0}\Setup", internalName);

    RegistryKey setupKey = baseKey.OpenSubKey(instanceSetupNode, false);

    if (setupKey != null)
    {
        // in the "Setup" node, you have several interesting items, like
        // * edition and version of that instance
        // * base path for the instance itself, and for the data for that instance
        string edition = setupKey.GetValue("Edition").ToString();
        string pathToInstance = setupKey.GetValue("SQLBinRoot").ToString();
        string version = setupKey.GetValue("Version").ToString();

        Console.WriteLine("\tEdition         : {0}", edition);
        Console.WriteLine("\tVersion         : {0}", version);
        Console.WriteLine("\tPath to instance: {0}", pathToInstance);
    }
}
+2
source

The most reliable answer is to use

DataTable instances = Microsoft.SqlServer.Smo.SmoApplication.EnumAvailableSqlServers(local: true);
0
source

Source: https://habr.com/ru/post/1608524/


All Articles