Question: How do I write a SQL script that will return the current database name in SQL Server?
Answer: Easy – select db_name();
The system function db_name() can be used to return this information.
The syntax for this command is: “DB_NAME ( [ database_id ] )” where database_id is the database id from sys.databases. If do not pass a value to the database_id parameter the DB_NAME function will return the name of the database that the script is currently executing in.
The following example returns the name of the current database.
--------------------------------------- select db_name() as [Current Database]; go ---------------------------------------
The following example returns the value “AdventureWorks” which is the name of the current database.
--------------------------------------- use AdventureWorks; go select db_name() as [Current Database]; go ---------------------------------------
If you have any given database id and want to know the corresponding database name all you have to do is pass the database id to the db_name() system function. On my sql server the AdventureWorks database has the dababase id ’13’ (This can be found by selecting from the sys.databases system catalog view or by using the db_id() system function).
The following example returns the name of the database with the database id of ’13’. Since the AdventureWorks database on my particular SQL server has database id ’13’ the following example will return ‘AdventureWorks’ regardless of which database I am in when I execute the query.
-------------------------------------- select db_name(13) as [Database Name]; go --------------------------------------