Getting the Name of the Server and Databases in SQL Server

In this article, I would like to show how to get the name of the server and databases in SQL Server. For example, when you need a database backup and restore with C#, you need the database and server name. In my previous article, I defined how to create a SQL Server Backup File with C#.

So let's have a look at a practical example of how to find the name of the server and databases in SQL Server.

In SQL Server

To find the name of the server

1.  Using sysservers 

The following query gives the name of the database and the server name:

Select *  from sysservers





2.  Using @@servername variable


Global variables are pre-defined system functions. Their names begin with an @@ prefix. The server maintains the values in these variables. @@servername variable provides the server name information or this variable returns the name of the service under which SQL Server is running.


Select @@servername as [ServerName]



3. To return the current database name

DB_NAME function is used to get the current database name.

SELECT DB_NAME() AS [Current Database]




4. To find the database names

If you want a list of all databases, just execute the following query in SQL Server Management Studio:

Select * from sysdatabases




Similar Articles