Two of the metadata functions available in SQL Server include DB_NAME()
and ORIGINAL_DB_NAME()
. Both functions are similar in that they return the name of a database. But they are also different. You definitely don’t want to confuse the two, as they serve different purposes.
In a nutshell, each function works as follows:
DB_NAME()
returns the name of a specified database. If you don’t explicitly specify a database, it returns the current database.ORIGINAL_DB_NAME()
returns the database name specified by the user in the database connection string.
Example 1 – Initial Connection
Consider the following connection string:
mssql-cli -S localhost -U sa -P bigStrongPassword!!! -d WideWorldImporters
This is the connection string I provided when using the mssql-cli command line tool to connect to SQL Server.
This connection string includes -d WideWorldImporters
, which means that the WideWorldImporters database will be the initial database. Once I get connected to SQL Server, my current database will be WideWorldImporters.
Here’s what I get when I run both functions after logging in with the above connection string:
SELECT DB_NAME() AS [Current Database], ORIGINAL_DB_NAME() AS [Original Database], DB_NAME(5) AS [Another Database];
Result:
+--------------------+---------------------+--------------------+ | Current Database | Original Database | Another Database | |--------------------+---------------------+--------------------| | WideWorldImporters | WideWorldImporters | MyDB | +--------------------+---------------------+--------------------+
Example 2 – Switch Databases
Here’s what happens if I switch to a different database and run the statement again:
USE Music; SELECT DB_NAME() AS [Current Database], ORIGINAL_DB_NAME() AS [Original Database], DB_NAME(5) AS [Another Database];
Result:
+--------------------+---------------------+--------------------+ | Current Database | Original Database | Another Database | |--------------------+---------------------+--------------------| | Music | WideWorldImporters | MyDB | +--------------------+---------------------+--------------------+
The current database changes, but original database remains the same. The third column also remains the same because I specified the same database ID (5
) when calling DB_NAME()
.
Example 3 – Default Database
Here’s what happens if I don’t explicitly specify a database in the connection string:
mssql-cli -S localhost -U sa -P bigStrongPassword!!!
Now run ORIGINAL_DB_NAME()
:
SELECT DB_NAME() AS [Current Database], ORIGINAL_DB_NAME() AS [Original Database], DB_NAME(5) AS [Another Database];
Result:
+--------------------+---------------------+--------------------+ | Current Database | Original Database | Another Database | |--------------------+---------------------+--------------------| | master | master | MyDB | +--------------------+---------------------+--------------------+
The default database for that user is used, which in this case is the master database.