Here are a couple of T-SQL methods you can use to return the server name in SQL Server.
@@SERVERNAME
The @@SERVERNAME
configuration function is designed specifically for returning the name of the local server that is running SQL Server.
To get the server name, you simply select it using a SELECT
statement.
SELECT @@SERVERNAME;
Result on my system:
mssql2019_1
This tells me that my server name is mssql2019_1
.
SERVERPROPERTY(ServerName)
The SERVERPROPERTY()
metadata function can also be used to return the server name, as well as many other properties.
To return the server name, you need to pass ServerName
as an argument.
SELECT SERVERPROPERTY('ServerName');
Result:
mssql2019_1
In my case, it’s the same output.
Difference Between These Two Functions
The two functions above produce the same output on my machine, but you might find that they produce slightly different output on yours.
The two functions are similar, but slightly different. Here’s the difference:
@@SERVERNAME
provides the currently configured local server name.- The
ServerName
property provides the Windows server and instance name that together make up the unique server instance.
So for example, on a Windows system, if your computer name is Felix
, and your SQL Server instance is called sql1
, running SERVERPROPERTY('ServerName')
might return Felix\sql1
.
The Machine Name & Instance Name
The SERVERPROPERTY()
function can also be used to return the machine name as well as the SQL Server instance name.
However, the results you get will depend on a couple of things (mentioned below).
Here’s what I get on my Mac running SQL Server for Linux via a Docker container.
SELECT
SERVERPROPERTY('MachineName') AS MachineName,
SERVERPROPERTY('InstanceName') AS InstanceName;
Result:
+---------------+----------------+ | MachineName | InstanceName | |---------------+----------------| | mssql2019_1 | NULL | +---------------+----------------+
First, the MachineName
property returns the machine name. Microsoft’s explanation is that it returns the Windows computer name on which the server instance is running.
Microsoft also states that “For a clustered instance, an instance of SQL Server running on a virtual server on Microsoft Cluster Service, it returns the name of the virtual server”.
As far as the InstanceName
property goes, it returns the name of the instance to which
the user is connected.
However, it returns NULL
if the instance name is the default instance, if the input is not valid, or error.
In my case, the instance name is the default instance and I got NULL
.