T-SQL Tutorial

How to get SQL Server instance name


SQL Server instance names are an important aspect of SQL Server configuration and management. In a server that hosts multiple instances of SQL Server, each instance is identified by its unique name. The instance name is used to differentiate between different SQL Server installations on the same physical server.

To retrieve the name of the SQL Server instance, you can use Transact-SQL (T-SQL) commands. T-SQL is the primary means of programming and managing SQL Server. Here are two methods to get the SQL Server instance name:


Using @@SERVICENAME

@@SERVICENAME returns the name of the registry key under which SQL Server is running. This is typically the same as the SQL Server instance name.

Example query:

SELECT @@SERVICENAME AS InstanceName;

This command returns the name of the instance for the current session.


Using SERVERPROPERTY

SERVERPROPERTY is a more versatile function that returns SQL Server instance information. The property name 'MachineName' returns the Windows computer name for the SQL Server instance, 'InstanceName' returns the instance name, and 'ServerName' returns the complete server name (which is a combination of machine name and instance name for named instances).

Example query to get instance name:

SELECT SERVERPROPERTY('InstanceName') AS InstanceName;

This approach is particularly useful for getting detailed information about the SQL Server instance.

Both methods are straightforward and can be executed in a query window in SQL Server Management Studio (SSMS) or any other tool that can run T-SQL queries. The choice between @@SERVICENAME and SERVERPROPERTY often depends on the specific requirements of your query and the level of detail you need about the SQL Server instance.