有一种方法可以检查哪个实例是Main / 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())
{
Console.WriteLine(ServerName + "\\" + instanceName);
}
}
}
}
查找所有实例。之后,我检查数据库是否存在于任何实例上。如果不是,我想在主实例上创建它。
根据MSDN,默认实例名称为MSSQLSERVER
:
默认实例名称为MSSQLSERVER;它不需要客户端指定实例名称即可建立连接。
因此,要定义实例是否为默认实例,必须检查实例的名称是否为MSSQLSERVER
。
这里可以对您的代码进行更改,以定义实例是否默认:
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);
}
}
}
}