sql - I am trying to use table variable as a dbname to iterate through multiple databases -
i trying execute following piece of code:
use projects set nocount on create table #t (dbname varchar(20), col2 datetime) declare @sql nvarchar(max) declare @proc_sql nvarchar(max) declare @table_car table (rowid int not null primary key identity(1,1), carrier varchar(500)) insert @table_car (carrier) select distinct t.db_name table t with(nolock) inner join table_t1 t1 with(nolock) on t.id = t1.id declare @rowstoprocess int declare @currentrow int declare @dbname varchar(500) set @rowstoprocess = @@rowcount set @currentrow = 0 while @currentrow < @rowstoprocess begin set @currentrow = @currentrow+1 select @dbname = carrier @table_car rowid = @currentrow select @sql = ' insert #t (dbname, col2) select distinct db_name(), col_x from'+@dbname+'..table_xyz' set @proc_sql = replace(@sql, @dbname, @dbname) exec (@proc_sql) end however, when execute this, getting error:
msg 102, level 15, state 1, line 3 incorrect syntax near '.'. which believe has nothing line 3 has syntax error near @dbname variable being used inside while loop. please help
i believe missing space between right after in "col_x from'+@db_name". should this:
select distinct db_name(), col_x '+@dbname+'..table_xyz' -------------------------------------^ one thing can print out sql strings when debugging , run them on own. easier debug. in example, instead of exec (@proc_sql) print @proc_sql.
Comments
Post a Comment