I'm writing a data migration script to import data from 3 separate DBs with identical schema into a new database. All databases reside on the same SQL Server instance.
It seems very wasteful to copy and paste the queries 3 times over:
insert NewTable(NewField1, NewField2)
select OldField1, OldField2
from OldDb1..OldTable
insert NewTable(NewField1, NewField2)
select OldField1, OldField2
from OldDb2..OldTable
insert NewTable(NewField1, NewField2)
select OldField1, OldField2
from OldDb3..OldTable
... and obviously it will be a nightmare to maintain if I need to tweak the script... plus I count myself lucky that there are only 3 databases, but what if there had been 100?
Bottom line, I would want to write a script that takes the database name as a parameter, so that I can just run one script 3 times, e.g.
create proc MigrateData(@db database)
as
insert NewTable(NewField1, NewField2)
select OldField1, OldField2
from @db..OldTable
...but of course that syntax won't work.
I could do this:
create proc MigrateData(@db varchar(50))
as
begin
declare @cmd varchar(max);
set @cmd = 'insert NewTable(NewField1, NewField2)
select OldField1, OldField2
from '+@db+'..OldTable';
exec @cmd;
end
But... yuck!
How do I do it?