0

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?

2 Answers 2

1

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.

1

I'm not 100% but shouldnt you use:

USE <DBNAME>
GO
SELECT <STATEMENT>

If i'm way off sorry about that.

2
  • 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. Dec 10, 2010 at 16:52
  • I think that if the DB ID specified dosnt not exist it simply returns the current database.
    – JamesK
    Dec 10, 2010 at 16:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .