The following query returns the name of the current database:
USE [DB1]
SELECT DB_NAME() AS Current_DB
FROM [dbo].[TblName]
Result:
Current_DB
----------
DB1
I'm seeing very strange results when using DB_NAME() with queries that SELECT FROM a table in [DBName].[SchemaName].[TblName] notation:
T-SQL
USE [DB1]
SELECT DB_NAME() AS Current_DB
FROM [DB1].[dbo].TblName
UNION
SELECT DB_NAME() AS Current_DB
FROM [DB2].[dbo].TblName
UNION
SELECT DB_NAME() AS Current_DB
FROM [DB3].[dbo].TblName
UNION
SELECT DB_NAME() AS Current_DB
FROM [DB4].[dbo].TblName
Result:
Current_DB
----------
DB1
T-SQL
USE [DB1]
SELECT DB_NAME() AS Current_DB
FROM [DB1].[dbo].TblName
UNION ALL
SELECT DB_NAME() AS Current_DB
FROM [DB2].[dbo].TblName
UNION ALL
SELECT DB_NAME() AS Current_DB
FROM [DB3].[dbo].TblName
UNION ALL
SELECT DB_NAME() AS Current_DB
FROM [DB4].[dbo].TblName
Result:
Current_DB
----------
DB1
DB1
DB1
... (632,788 rows of DB1 !!!)
Even if I omit the USE [DB1] from T-SQL query, I get the same results - the database selected in the Query Target dropdown menu of SSMS is the one appearing in the results.
How can I get the correct DB_NAME() across multiple queries using [DBName].[SchemaName].[TblName] format?
returns the name of the current database. Not the database of the table(s) in the FROM clause.DB_NAME()to return the name you want is to douse [dbname]first. And if you can do that, you already have the name...