Saturday, August 06, 2011

DB_ID (Function)

 

DB_ID () function returns int valued ID of the supplied database. If no argument is provided then it return the ID of the current database.

1. To find the ID of current database:-

select DB_ID( ) as Database_ID;

go

select DB_ID(‘AdventureWorks2008R2’) ad Database_ID;

go

2. 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 AdventureWorks2008R2 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'AdventureWorks2008R2');
SET @object_id = OBJECT_ID(N'AdventureWorks2008R2.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

No comments: