I need to query all databases on a server. I cursor through all the databases and assign each next to a variable @DB

I can then use @DB by executing SQL from within the cursor and this is all fine until I need to do another if exists to handle databases which don't contain a status I need to check. Code below.

Thanks,

```
set nocount on
use [master]
declare @DB sysname
declare @sql nvarchar(max)
declare curDB cursor for
select [name] from sysdatabases
order by name

create table #results (
[Database] nvarchar(max),
[CompanyCode] nvarchar(max),
[Title] nvarchar(max),
[Status] nvarchar(max)
)

use [master]
open curDB
fetch next from curDB into @DB
while @@FETCH_STATUS=0
begin

set @sql = 'use [' + @DB + ']; if exists(select 1 from sys.tables where name=''Licence'')
begin

Insert into #results
Select
DB_NAME() as ''Databas'',
Company as ''CompanyCode'',
Title as ''Title''
'

use @DB; --This is what i'm struggling with because the if exists check below is checking against master, i need it to check the current @DB from curDB
if exists (select 'X' from sys.columns where name = 'DocumentLevelInvoiceMatching')

    begin
        set @sql = @sql + 'Case when Status = 1 then ''NewEngine'' else ''OldEngine'' end as ''MatchingEngine''
        from dsdba.companies
        end
        '
    end
else
    set @sql = @sql + '''Old Engine''
    from dsdba.companies
    end
    '

use master
exec (@sql)
fetch next from curDB into @DB
end

use CentralDatabase

IF OBJECT_ID('dbo.CompanyConfiguration', 'U') IS NOT NULL 
  DROP TABLE dbo.CompanyConfiguration; 

use master
select * into CentralDatabase.dbo.CompanyConfiguration
from #results

Select * from CentralDatabase.dbo.CompanyConfiguration
close curDB
deallocate curDB

drop table #results

```