Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I recently saw that when I issue

select DB_NAME(0) 

there is some answer, and when I check sys.databases there is no DB ID 0, so I think there should be a NULL return. If I select DB_NAME(1000) and there is no db id 1000 the return is NULL.

I noticed that the database I'm currently using is always displayed.

Is this normal? is this a bug or something?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

I do not think that any database would have an id of zero, or a negative number. According to the official Microsoft Books Online documentation for db_name():

Arguments: database_id Is the identification number (ID) of the database to be returned. database_id is int, with no default. If no ID is specified, the current database name is returned.

So, I would say that the behavior sort of interesting, but that it is undefined and should not be relied on for production code.

I've always used db_name(), with no parameters, to find the name of the current database.

share|improve this answer

I'm not 100% but shouldnt you use:

USE <DBNAME>
GO
SELECT <STATEMENT>

If i'm way off sorry about that.

share|improve this answer
    
you made me notice that the database I'm using is the one that gets displayed. So if I: USE MASTER GO SELECT DB_NAME(0) I get MASTER as answer. But I'm still wondering why is this, I think this shouldn't happen. –  Gabriel Guimarães Dec 10 '10 at 16:52
    
I think that if the DB ID specified dosnt not exist it simply returns the current database. –  JamesK Dec 10 '10 at 16:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.