Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

How To Get The Database Name For The Current User Process

From Wiki

Jump to: navigation, search

Here are 4 ways to return the database name for the current user process

First up is the fastest method. this will run on SQL Server 2000, 2005 and 2008

  1. SELECT DB_NAME()


Next up is getting the name by joining the sys.dm_exec_requests dmv and sys.sysdatabases. this runs on SQL Server 2005/2008 only

  1. SELECT s.name
  2. FROM sys.dm_exec_requests d
  3. JOIN sys.sysdatabases s ON d.database_id = s.dbid
  4. WHERE session_id = @@SPID


Here is something similar, this also runs only on SQL Server 2005/2008

  1. SELECT name
  2. FROM sys.sysdatabases
  3. WHERE dbid = DB_ID()


And we end with something that runs on SQL Server 2005 ,2008 and 2000

  1. SELECT name
  2. FROM master..sysdatabases
  3. WHERE dbid = DB_ID()


But like I said before you should always use DB_NAME()


Contributed by: --SQLDenis 16:49, 23 June 2008 (GMT)

Part of SQL Server Admin Hacks

418 Rating: 0.0/5 (0 votes cast)