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 SQL Server and T-SQL Development Tutorials
Development resources, articles, tutorials, samples, codes and tools for .Net, SQL Server, Windows, Windows Phone, SAP and ABAP, like SAP UI5, Screen Personas, etc.




download SQL Server 2016
download SQL Server 2014
download SQL Server 2012



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







Related SQL Resources

SQL Server Articles

SQL Server 2012

SQL Server Tools

SQL Blog

SQL Server 2008 Blog

Certification Exams Blog

Reporting Services Blog

Analysis Services Blog

MS SQL Server Forums







Copyright © 2004 - 2017 Eralper YILMAZ. All rights reserved.
Community Server by Telligent Systems