DB_NAME() when looping through multiple databases

30 Views Asked by At

I have the following piece of script that loops through multiple identical databases (55 of them). I am trying to get the database name as a column, but it keeps giving me the master db_name as this is where I execute from. When I change it to something else, then I get that db_name, but never the correct one based on the database in question.

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + N'
UNION ALL 
SELECT top 1
    Account as Account,
    DB_NAME() as DatabaseName,
    (Select CompnyName from ' + QUOTENAME(name) + '.dbo.OADM)as Entity,
    GL.TransId as TransactionId,    
        isnull(Debit,0) as Debit,
        isnull(Credit,0) as Credit,
        isnull(Debit,0)- isnull(Credit,0) as Balance,
        year(GL.refdate)*10000+month(GL.refdate)*100+day(GL.refdate) as TimePeriod
FROM ' + QUOTENAME(name) + '.dbo.JDT1 GL'
FROM master.sys.databases WHERE 
state = 0 
and database_id > 8 
and name not like '%template%'
and name not like '%staging%'
and name not like '%test%'

SET @sql = STUFF(@sql, 1, 11, '');

EXEC  (@sql);
--Print @sql

The rest works great, it is just the db_name that I need added.

Please help. Thanks, Wynand

I tried using DB_ID() with and without quotes, but it keeps executing against the master database.

0

There are 0 best solutions below