Get Current Database Name in SQL Server using DB_NAME
Using built-in DB_NAME() SQL function, developers can get current database name that they are executing their scripts on.
If your database programmer is creating SQL scripts that will execute on many SQL Server databases, there may be a beed to customize the scripts by using the database name.
In such cases, developers have to find the database name programmatically in their SQL codes where DB_NAME() SQL Server function helps.
Beside current databe, if you pass database id parameter to DB_NAME() sql function, it will return the name of the SQL database with given database id property in sys.databases system view
Let's use DB_NAME() function to get current database name.
select DB_NAME() as [Current Database]
As you see in below screenshot, DB_NAME() function without any database id parameter returns the current SQL database name in the select list.
If you want to know other database's name which you know the database_id value of it, you can pass database_id value as an input argument to the DB_NAME() SQL Server function as seen in below SQL Select statement.
In the second Select list from sys.databases system view, all existing databases with their database id values and names are listed.
select DB_NAME(1)as [Database Name]
select database_id, name from sys.databases
Here is the output of the SQL statements where DB_NAME() function is used