简体   繁体   中英

Get default SQL Server Instance On Local Machine Using C#

There is way to check which instance is Main/Default.

I use this

 private void GetDataSources2()  
 {  
     string ServerName = Environment.MachineName;  

     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(ServerName + "\\" + instanceName);  
             }  
         }  
     }  
 } 

To find all instance. After it I check whether the database exists on any instance. If not I want to create it on main instance.

According to MSDN default intance name is MSSQLSERVER :

The default instance name is MSSQLSERVER; it does not require a client to specify the name of the instance to make a connection.

Therefore to define if an instance is default it is necessary to check if the name of the instance is MSSQLSERVER .

Here are changes that can be made to your code to define if an instance is default:

private void GetDataSources2()
{
    string ServerName = Environment.MachineName;

    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 (instanceName == "MSSQLSERVER")
                    // To reference default instance we should use name "ServerName".
                    Console.WriteLine(ServerName);
                else
                    // To reference non default instances we should use name "ServerName\InstanceName".
                    Console.WriteLine(ServerName + "\\" + instanceName);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM