BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

SQL Server
SQL 2005+

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.

DB_Name

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.

SELECT db_name()
17 February 2014