Export (0) Print
Expand All
Expand Minimize
6 out of 7 rated this helpful - Rate this topic

DB_ID (Transact-SQL)

Returns the database identification (ID) number.

Topic link icon Transact-SQL Syntax Conventions


DB_ID ( [ 'database_name' ] ) 
' database_name '

Is the database name used to return the corresponding database ID. database_name is sysname. If database_name is omitted, the current database ID is returned.

A. Returning the database ID of the current database

The following example returns the database ID of the current database.

SELECT DB_ID() AS [Database ID];
GO

B. Returning the database ID of a specified database

The following example returns the database ID of the AdventureWorks database.

SELECT DB_ID(N'AdventureWorks') AS [Database ID];
GO

C. Using DB_ID to specify the value of a system function parameter

The following example uses DB_ID to return the database ID of the AdventureWorks database in the system function sys.dm_db_index_operational_stats. The function takes a database ID as the first parameter.

DECLARE @db_id smallint;
DECLARE @object_id int;
SET @db_id = DB_ID(N'AdventureWorks');
SET @object_id = OBJECT_ID(N'AdventureWorks.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

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.