DECLARE @Table TABLE ( instanceName sysname NULL)
insert @Table EXEC sys.xp_cmdshell 'sqlcmd -Lc'
--LEFT(@@serverName,CHARINDEX('/',@@serverName+'/')-1) 替代為本機名就行了 , 根據實例命名規則判斷
SELECT * FROM @Table WHERE instanceName LIKE LEFT( @@serverName , CHARINDEX ( '/' , @@serverName + '/' )- 1)+ '%'
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);
}
}
}
}
}
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;
}