SQL Server services are called either MSSQLSERVER (default instance) or MSSQL $ INSTANCENAME (named instances). You can determine whether it is a named instance or from a connection string (if it is in the form host\instance , a named instance, if is host , then it is the default instance), but, in truth, it is not, because:
- connection string can use SQL client alias
- the connection string can connect to a named instance listening on the default port
- the connection string can connect to an explicit port and not specify an instance name
Thus, a more reliable way is to connect and query the instance name:
SELECT SERVERPROPERTY('InstanceName');
If the return is NULL, the service name will be MSSQLSERVER, otherwise MSSQL $ ... You can even set this directly in the query:
SELECT COALESCE('MSSQL$'+cast(SERVERPROPERTY('InstanceName') as sysname), 'MSSQLSERVER');
source share