title: Looping each record of a table and inserting data into a temp table joining another temp table in SQL
body: <p>I have two temporary table  <code>#CoreUtilizationForRole1</code> and  <code>#RoleID2Details</code>. I want to insert values into a third temp table using these two temp table.
  Below are the table Structure of both the Temp table.</p>
  
  <pre><code>create table #CoreUtilizationForRole1(roleid int,SupervisorName varchar(50),ImmediateSupervisor varchar(50),UserECode varchar(50),UserName nvarchar(250),Designation varchar(250),TimeSpent float,ActivityName varchar(250))
  
  create table #RoleID2Details(UserECode varchar(50),UserName nvarchar(250))
  </code></pre>
  
  <p>in <code>#CoreUtilizationForRole1</code> table I had generated a report and stored in it. <code>#RoleID2Details</code> contains data as mentioned below in the query:-</p>
  
  <pre><code>insert into #RoleID2Details
      select distinct Userecode,Username from #CoreUtilizationForRole1 where roleid=2
  </code></pre>
  
  <p>Now I want to loop through each records of  <code>#RoleID2Detail</code>s and insert data into a third temp table while joining from <code>#CoreUtilizationForRole1</code>.
  AcTually I need data in a particular described format and due to that, this looping is required so that I insert data into third temp table as per my requirement and then using a simple select statement I will display it.</p>
  
  <p>The third table Structure will be -</p>
  
  <pre><code>create table #ThirdtempTable(roleid int,SupervisorName varchar(50),ImmediateSupervisor varchar(50),UserECode varchar(50),UserName nvarchar(250),Designation varchar(250),TimeSpent float,ActivityName varchar(250))
  </code></pre>
  
  <p>and the logic for inserting data into <code>#ThirdtempTable</code> is like this looping each records of <code>#RoleID2Details</code> table-</p>
  
  <pre><code>insert into #ThirdtempTable
  Select A.RoleId,A.SuperVisorName,A.Userecode,A.Username,A.Designation,A.TimeSpent,A.ActivityName 
  from #CoreUtilizationForRole1 A 
  inner join #RoleID2Details B 
  on
  A.SuperVisorName=B.UserName
  where B.UserECode= --First UserECode from #RoleID2Details
  
  insert into #ThirdtempTable
  Select A.RoleId,A.SuperVisorName,A.Userecode,A.Username,A.Designation,A.TimeSpent,A.ActivityName 
  from #CoreUtilizationForRole1 A 
  inner join #RoleID2Details B 
  on
  A.UserName=B.UserName
  where A.UserECode=--First UserECode from #RoleID2Details
  </code></pre>
  
  <p>this looping will go until we extract all the records from <code>#RoleID2Details</code> table and insert it as mentioned above into <code>#ThirdtempTable</code> table.</p>