title: Generic Table Name Executed in a Loop
body: <p>I have a db with many companies in it. What I am trying to is, I want to insert data to each company's table's from a different db which also has the same companies and tables in it. I created a loop using a table that contains the company names and in that loop I would like to insert from one db to another by generating the table name in loop. I created a loop which gives me the company names in it but I couldn't find the way to use results to generate the object name. My query is like;</p>
  
  <pre><code>declare @Rowcount int 
  select @Rowcount=count(*) from [DB_1].[dbo].[Companies];
  
  while( @Rowcount&gt;0)
  begin 
  
  //Begin Insert Data From DB_1 to DB_2 with sames company names
  INSERT INTO [DB_1].[dbo].[**[DB_1].[dbo].[Companies].[CompanyName]**$SomeTable]           
         ([Field_1],
          [Field_2])
  SELECT
          [Field_1],
          [Field_2]
  FROM [DB_2].[dbo].[**[DB_1].[dbo].[Companies].[CompanyName]**$SomeTable]
  //End Insert Data From DB_1 to DB_2 with sames company names
  
  SELECT @Rowcount=@Rowcount-1;  
  SELECT Name FROM [DB_1].[dbo].[Companies] order by Name desc OFFSET @Rowcount ROWS FETCH NEXT 1 ROWS ONLY;
  end 
  </code></pre>
  
  <p>So basically I couldnt find a way to generate [DB_1].[dbo].[Companies].[CompanyName] as a variable to use in insert query.</p>
  
  <p>I will be more than happy if you can show me how to generate the company name in the loop and use it inside the insert query.</p>
  
  <p>Thanks and Regards,
  Ararat</p>