SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

DB_NAME() vs ORIGINAL_DB_NAME()

I’d never seen ORIGINAL_DB_NAME until recently and I thought it would be interesting to highlight it out, and in particular the difference between it and DB_NAME. I use DB_NAME and DB_ID fairly frequently in support queries (for example what database context is a query running from or what database are given DB files from). So starting with DB_NAME.

DB_NAME

Simply enough, if you pass a database_id in, it returns the databases name, if you don’t it returns the current databases name.

USE tempdb;
SELECT DB_NAME();
SELECT DB_NAME(3);

ORIGINAL_DB_NAME

You might think this is always the database the connection initially connected to but you would be wrong. In fact, it returns a blank unless you specify a database to connect to in your connection string or connection options, etc. USE has no effect on the output and neither does your default database. There is also no parameter so this is the only value it will show. Using SQLCMD to make this a bit easier to see:

Without specifying -d (connect to a specific database)

With specifying -d

VS

Honestly, the only possible use I can see for ORIGINAL_DB_NAME is for some forms of logging/auditing. Good information to know, but I’ll still be using DB_NAME 99% of the time.

SQLStudies

My name is Kenneth Fisher and I am Senior DBA for a large (multi-national) insurance company. I have been working with databases for over 20 years starting with Clarion and Foxpro. I’ve been working with SQL Server for 12 years but have only really started “studying” the subject for the last 3. I don’t have any real "specialities" but I enjoy trouble shooting and teaching. Thus far I’ve earned by MCITP Database Administrator 2008, MCTS Database Administrator 2005, and MCTS Database Developer 2008. I’m currently studying for my MCITP Database Developer 2008 and should start in on the 2012 exams next year. My blog is at www.sqlstudies.com.

Comments

Leave a comment on the original post [sqlstudies.com, opens in a new window]

Loading comments...