How to Get Server Name in SQL Server using Query?

In this SQL Server tutorial, you will learn how to get server name in SQ Server using query.

In this tutorial, you will understand two configuration functions in SQL Server which help in finding the name of the SQL Server.

Get Server Name in SQL Server using Query

To get server name in SQ Server using query, SQL Server provides two methods. The first method uses the @@SERVERNAME configuration function and the second uses SERVERPROPERTY() function.

So open the command prompt and connect to the SQL Server instance using the SQLCMD utility.

In the command line write the below query to find the name of the current server.

SELECT @@SERVERNAME;
GO
@@SERVERNAME Function to Get Server Name in SQL Server using Query

When you execute the above query it returns the server name MSI\SQLEXPRESS which is the name of the current server to which you are connected. The name of the server can be different in your case, it depends on how you have configured your SQL Server.

In the query, @@SERVERNAME is a function that retrieves the name of the server where SQL is running.

After this, the next function that you can use to get the name of the server is SERVERPROPERTY(ServerName). So write the below query to get the server name.

SELECT SERVERPROPERTY('ServerName');
SERVERPROPERTY Function to Get Server Name in SQL Server using Query

The above query also returns the server name MSI\SQLEXPRESS, here function SERVERPROPERTY accepts the string value ‘ServerName’ to return the value of the server name property.

This is how to get server name in SQL Server using query.

Conclusion

In this SQL Server tutorial, you have learned how to find the name of the SQL Server using query, where you learned about two functions @@SERVERNAME and SERVERPROPERTY in SQL Server.

You may like the following: