Using variable for database name I am having difficulty in using a variable name for the database. The below script searches through all databases and finds database that match a certain condition. The matching databases are added to table #t.
I then loop through each database by setting the @DB1 to each database in turn. The problem I'm getting is when it comes to using the database name in @DB1. Any idea how I can get each of my matching databases to update?

create table #t (
    ID int IDENTITY,DBName sysname not null
)
go
EXEC sp_MSforeachdb 'use [?]; if OBJECT_ID(''dbo.SDE_server_config'') is not null insert into #t (DBName) select ''?'''



Declare @RowCount int
Declare @Counter int
Declare @DB1 varchar(max)

set @RowCount = (Select Count(*) from #t)
set @Counter=0


While @Counter &lt;= @RowCount
Begin
select @Counter = @Counter + 1


set @DB1 =  = (select DBName FROM #t WHERE ID = @COUNTER)

:SETVAR DatabaseName @DB1



USE $(DatabaseName);

UPDATE dbo.SDE_server_config
        SET num_prop_value=0
        WHERE prop_name=CONNECTIONS;

End
You dont really need a loop and there is no need to use the undocumented sp_MSforeachdb as there is a better alternative to it - written by Aaron Bertrand.

You can use below tsql - Run in SSMS by pressing CTRL+T:

set nocount on

select 'if OBJECT_ID(''dbo.SDE_server_config'') is not null'+char(10)+'begin '+char(10)+' UPDATE ' + quotename(name) + '.dbo.SDE_server_config SET num_prop_value=0
        WHERE prop_name=CONNECTIONS;' + char(10) + 'end '+char(10)+ 'else print ''there is nothing to update ...!;'''
from sys.databases
where database_id &gt; 4
    and state_desc = 'ONLINE'


You can put above select statement in a variable and do and EXEC and save it in a .sql file and then use sqlcmd to just directly call that .sql file and run it on multiple servers.