How DB_NAME() Works in SQL Server

In SQL Server, you can use the DB_NAME() function to return the name of the current database, or another specified database.

The way it works is, you pass the ID of the database as an argument, and then the function will return the name of that database. However, if you don’t pass an ID it will return the name of the current database.

Example 1 – Return the Current Database

Here’s a basic example to demonstrate how to return the name of the current database.

SELECT DB_NAME() AS [Current Database];

Result:

+----------------------+
| Current Database     |
|----------------------|
| WideWorldImportersDW |
+----------------------+

In this case, the current database is called WideWorldImportersDW.

Here’s another example that demonstrates it further, by switching databases.

USE Music;
SELECT DB_NAME() AS [Current Database];

USE EMS;
SELECT DB_NAME() AS [Current Database];

USE WideWorldImportersDW;
SELECT DB_NAME() AS [Current Database];

Result:

Changed database context to 'Music'.
+--------------------+
| Current Database   |
|--------------------|
| Music              |
+--------------------+
(1 row affected)
Changed database context to 'EMS'.
+--------------------+
| Current Database   |
|--------------------|
| EMS                |
+--------------------+
(1 row affected)
Changed database context to 'WideWorldImportersDW'.
+----------------------+
| Current Database     |
|----------------------|
| WideWorldImportersDW |
+----------------------+
(1 row affected)

Example 2 – Return a Specific Database

Here’s an example of returning a specific database. This is done by passing in the ID of the database.

SELECT DB_NAME(6) AS Result;

Result:

+----------------------+
| Result               |
|----------------------|
| WideWorldImportersDW |
+----------------------+

And while we’re at it, here are a few more:

SELECT 
  DB_NAME(1) AS [1],
  DB_NAME(2) AS [2],
  DB_NAME(3) AS [3],
  DB_NAME(4) AS [4],
  DB_NAME(5) AS [5],
  DB_NAME(6) AS [6];

Result:

+--------+--------+-------+------+-------+----------------------+
| 1      | 2      | 3     | 4    | 5     | 6                    |
|--------+--------+-------+------+-------+----------------------|
| master | tempdb | model | msdb | Music | WideWorldImportersDW |
+--------+--------+-------+------+-------+----------------------+