Obtaining the Current Database Name
When developing stored procedures or functions that are to be reused by multiple databases, it may be necessary to obtain the name of the current database. This can be achieved using a metadata function.
If you are creating library functions, procedures or scripts for use with SQL Server, you may need to obtain the name of the current database. For example, you may decide to create a stored procedure that performs logging in a standardised format. In this situation you might wish to read the database name so that you can record the source of the log.
Transact-SQL includes a number of metadata functions. One of these is DB_Name. When called, the function returns the name of a database as an NVARCHAR value. You can pass an integer value as an argument if you wish to find the name of a database for which you know the database ID. To get the current database's name, call the function with no parameters.
17 February 2014