When running queries in SQL Server, you’ll need to know which database your query is running against. If you’re using a GUI tool like SSMS, you’ll usually see the database expanded in the object explorer. Perhaps you even navigated to the database before opening a query window. In such cases, there will be no doubt which database you’re querying.
But when running T-SQL in a command line tool it’s not normally so apparent which database we’re working with. Also, you may be writing a script that needs to include the database name. Such scripts can be much more portable when they fetch the current database name dynamically (as opposed to having it hardcoded).
Fortunately SQL Server provides us with a function that makes it easy to find out the current database.
Using the DB_NAME() Function
SQL Server’s DB_NAME() function is made specifically to get the name of a given database. By default it returns the name of the current database. When I say “by default”, I mean, when we call it without any arguments:
SELECT DB_NAME();
For example:
USE WideWorldImporters;
SELECT DB_NAME();
Result:
WideWorldImporters
Here, I set WideWorldImporters as the current database, then called DB_NAME(). The DB_NAME() function simply returned the name of the current database.
You can also pass a database ID to retrieve the name of a specific database:
SELECT DB_NAME(1);
Output:
master
The master database is usually the first one in the list.
So to summarize:
- With no arguments,
DB_NAME()returns the name of the current database. - Passing a database ID retrieves the name of the database with that ID (or
NULLif none have that ID).
Using DB_ID() Along with DB_NAME()
If you want both the ID and name of the current database, you can combine DB_ID() with DB_NAME():
SELECT DB_ID() AS CurrentDatabaseID,
DB_NAME() AS CurrentDatabase;
Output:
CurrentDatabaseID CurrentDatabase
----------------- ------------------
8 WideWorldImporters
This time we get to see the ID of the current database, as well as its name.
Querying the sys.databases Catalog View
Another way to get the name of the current database is to query sys.databases. This system catalog view stores information about all databases on the SQL Server instance. We can use DB_ID() to filter for the current database:
SELECT name AS CurrentDatabase,
database_id,
create_date,
compatibility_level,
state_desc
FROM sys.databases
WHERE database_id = DB_ID();
Output:
CurrentDatabase database_id create_date compatibility_level state_desc
------------------ ----------- ------------------------ ------------------- ----------
WideWorldImporters 8 2021-10-06T22:08:52.490Z 130 ONLINE
This method can be helpful when you also need metadata (creation date, state, compatibility level, etc.).