SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP

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.

database name in SQL Server

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

get database name using DB_NAME() function

SQL Server

SQL Server 2019 Installation
download SQL Server 2019
download SQL Server 2017
download SQL Server 2016
download SQL Server 2014
download SQL Server 2012
MacOS ve SQL Server 2019

Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.