Latest Post

Monday, 8 May 2017

SQL Server Built-In Functions: DB_ID () and DB_NAME ()


SQL Server – Use DB_ID() and DB_NAME() to return current database ID and current database name

Sql Server provide two functions DB_ID() and DB_NAME() that return current database ID and current database name. DB_ID () provides the database ID of the current database. DB_NAME ()  provides the current database name.

Here is example of DB_ID()

-- Get Current DatabaseID
SELECT DB_ID() DatabaseID;

-- Get DatabaseID from DatabaseName
SELECT DB_ID('IFM_DEV_V1.1') DatabaseID;

Here is example of DB_NAME()

-- Get Current DatabaseName
SELECT DB_NAME() DatabaseName;


-- Get DatabaseName from DatabaseID
SELECT DB_NAME(8) DatabaseName;

To get all Database Name and DBID in sql server , you can use below query to get this.


-- Get all Database Name and DBID
SELECT name,database_id FROM sys.databases;

Output:-
name
database_id
master
1
tempdb
2
model
3
msdb
4
ReportServer$SS_DE_2014
5
ReportServer$SS_DE_2014TempDB
6
IFM_DEV_V1.0
7
IFM_DEV_V1.1
8


Government Jobs