Probably not even close to the best way... but 1 of 100 ways you can do it.
declare @databasename nvarchar(100) = 'roflcopter'
, @destination = 'myschema.mytable'
declare @companylist nvarchar(max) = (select stuff( select ',' +convert(nvarchar(5),companyid) from companytable where database = @databasename),1,1,'')
declare @query nvarchar(max)
= N'use ['+@databasename+']
insert into '+@destination+' /* maybe add dynamic columns here */
select /*same dynamic columns */
from mytable /*or another variable*/
where companyid in('''+@companylist+''')
'
exec (@query)
add your other variables and such to declare destination, future database name (if creating) and anything you want... dynamic sql can be slow, cumbersome and does reconnect. Might want to check the sp_executesql for differences between exec () and executesql
there are a ton of system procedures... ones that find FKs, column names, data types, pks... you can complicate it by building dynamically creating your current schema using (no help from me here) those system procedures, C# to easily 'generate scripts' and execute them.
May also be in the wrong direction you were thinking of.