简体   繁体   English

使用 C# 在本地计算机上获取默认 SQL 服务器实例

[英]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 :根据MSDN默认实例名称是MSSQLSERVER

The default instance name is MSSQLSERVER;默认实例名称是 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 .因此,要定义实例是否为默认实例,有必要检查实例的名称是否为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);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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