sql - Keeping variable scope throughout a script -
i have script has number of select statements connects various linked servers.
i want able run script multiple times in each case servers , databases change , couple of table names change.
i hoping use variables define servers once @ beiginning follows, of course goes out of scope local variables.
declare @table_that_changes varchar(100) declare @linked_server1 varchar(20) declare @linked_server2 varchar(20) declare @db_onserver1 varchar(100) declare @db_onserver2 varchar(100) select @linked_server1 = '[server109]', @linked_server2 = '[server104]', @db_onserver1 = '[database203434]', @db_onserver2= '[database416541]', @table_that_changes = 'losstable_2191'
what's best way store these values equivilant of (for example)
select * @linked_server1.@db_onserver1.dbo.table1
that works throughout script contains lots of select statements?
not want, 1 approach script views on tables remote servers using dynamic sql along lines of (not tested)
declare @table_that_changes varchar(100) declare @linked_server1 varchar(20) declare @linked_server2 varchar(20) declare @db_onserver1 varchar(100) declare @db_onserver2 varchar(100) select @linked_server1 = '[server109]', @linked_server2 = '[server104]', @db_onserver1 = '[database203434]', @db_onserver2= '[database416541]', @table_that_changes = 'losstable_2191' declare @sql varchar(1000) set @sql = 'create view linked1.table1 select * ' + @linked_server2 + '.' + @db_onserver1 + '.table1' exec( @sql)
Comments
Post a Comment