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#. 

http://www.c-sharpcorner.com/UploadFile/rohatash/creating-sql-server-backup-file-with-C-Sharp/#ReadAndPostComment

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

 

Output


Server-name-with-global-variable-in-SQL-Server.jpg

 

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]

Output

Server-name-in-SQL-Server.jpg

3. To return the current database name

DB_NAME function is used to get the current database name.

SELECT DB_NAME() AS [Current Database]

 

Output


Current-Database-Name-in-SQL-Server.jpg

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

Output

Database-Name-in-SQL-Server.jpg

 


Similar Articles