How To Get The Database Name For The Current User Process
From Wiki
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
- 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
- SELECT s.name
- FROM sys.dm_exec_requests d
- JOIN sys.sysdatabases s ON d.database_id = s.dbid
- WHERE session_id = @@SPID
Here is something similar, this also runs only on SQL Server 2005/2008
- SELECT name
- FROM sys.sysdatabases
- WHERE dbid = DB_ID()
And we end with something that runs on SQL Server 2005 ,2008 and 2000
- SELECT name
- FROM master..sysdatabases
- 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


