DB_NAME() System Function in SQL Server

In this blog, let’s take a look at a SQL Server System function, DB_NAME() .

This function is pretty handy when writing scripts that need you to identify the the Database name based on Database ID.


DB_NAME() function accepts an optional integer parameter (database_id) and returns the database name of that database_id, if no parameter is mentioned it returns the database name of the current database in whose context the script session is being executed. Let’s look at examples to understand it.

In the following picure, the function DB_NAME() returns the name of the database whose database_id is 1. Since the parameter value is passed on it returns the database name of that database_id, even though the query is running in the database SampleDataBase.

In the next example we look at how this function behaves when the optional parameter is not passed.


The result in this query is the database name in which the  query is executed. It returns the database name under whose contect the query is run, when there is a requirement to capture the database name through script, this can be used.

You may also want to take a look at this blog which explains about renaming the Database and the Database objects using T-SQL command. http://learnsqlwithbru.com/2010/03/01/renaming-database-and-database-objects-using-t-sql/

Do you like this site? Like our FB page @ Facebook.com\LearnSQLWithBru so that, you know when there is a new blog post.

–Bru Medishetty