Select Case When SERVERPROPERTY ('InstanceName') Is Null Then @@SERVERNAME Else SERVERPROPERTY ('InstanceName') End
五、在本地或网络得到所有实例名
1、You can do with registry reading , like my code
using System; using Microsoft.Win32;
namespace SMOTest { class Program { static void Main() { RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE/Microsoft/Microsoft SQL Server"); String[] instances = (String[])rk.GetValue("InstalledInstances"); if (instances.Length > 0) { foreach (String element in instances) { if (element == "MSSQLSERVER") Console.WriteLine(System.Environment.MachineName); else Console.WriteLine(System.Environment.MachineName + @"/" + element); } } } } }
2、You can use SQLDMO.dll to retrieve the list of SQL Server instances. The SQLDMO.dll can be found from the "C:/Program Files/Microsoft SQL Server/80/Tools/Bin" folder. Refer this assembly in your project and the following snippet would return a List Object containing the sql server instances.
public static List GetSQLServerInstances() { NameList sqlNameList = null; Application app = null;
var sqlServers = new List(); try { app = new ApplicationClass(); sqlNameList = app.ListAvailableSQLServers(); foreach (string sqlServer in sqlNameList) sqlServers.Add(sqlServer); } catch(Exception ex)
{
//play with the exception.
}
finally
{
if (sqlNameList != null) sqlNameList = null; if (app != null) app = null; } return sqlServers; }