This function returns the database identification (ID) number of a specified database.
Transact-SQL Syntax Conventions
‘database_name’
The name of the database whose database ID number DB_ID will return. If the call to DB_ID omits database_name, DB_ID returns the ID of the current database.
int
DB_ID may only be used to return the database identifier of the current database in Azure SQL Database. NULL is returned if the specified database name is other than the current database.
If the caller of DB_ID does not own a specific non-master or non-tempdb database, ALTER ANY DATABASE or VIEW ANY DATABASE server-level permissions at minimum are required to see the corresponding DB_ID row. For the master database, DB_ID needs CREATE DATABASE permission at minimum. The database to which the caller connects will always appear in sys.databases.
[!IMPORTANT]
By default, the public role has theVIEW ANY DATABASEpermission, which allows all logins to see database information. To prevent a login from detecting a database,REVOKEtheVIEW ANY DATABASEpermission from public, orDENYtheVIEW ANY DATABASEpermission for individual logins.
This example returns the database ID of the current database.
This example returns the database ID of the **AdventureWorks2012** database.
This example uses DB_ID to return the database ID of the **AdventureWorks2012** database in the system function sys.dm_db_index_operational_stats. The function takes a database ID as the first parameter.
DECLARE @db_id int;
DECLARE @object_id int;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
BEGIN;
PRINT N'Invalid database';
END;
ELSE IF @object_id IS NULL
BEGIN;
PRINT N'Invalid object';
END;
ELSE
BEGIN;
SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
END;
GO This example returns the database ID of the current database.
This example returns the database ID of the AdventureWorksDW2012 database.
DB_NAME (Transact-SQL)
Metadata Functions (Transact-SQL)
sys.databases (Transact-SQL)
sys.dm_db_index_operational_stats (Transact-SQL)