Wednesday, March 14, 2007

How To Get The Database Name For The Current User Process

This question pops up frequent enough so 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 200 and 2005

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 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

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


And we end with something that runs on both SQL Server 2005 and 2000
SELECT name
FROM master..sysdatabases
WHERE dbid = DB_ID()


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

1 comment:

Anonymous said...

Thanks.