title: Insert Selected Data From Multiple table to a single table
body: <p>I have following table structure in SQL Server 2005.</p>
  
  <ol>
  <li>AttendanceDetail (<code>AttenID, Date, EmpID,....</code>)</li>
  <li>A_OfficialDetail (<code>AttenID, OfficeOut, OfficeIn</code>)</li>
  <li>A_Personal Detail (<code>AttenID, OfficeOut, OfficeIn</code>)</li>
  <li>A_RecessDetail (<code>AttenID, OfficeOut, OfficeIn</code>)</li>
  <li>Atten_Temp_AttenDetail** (<code>EmpID, AttenID, Detail, OfficeOut, OfficeIn</code>)</li>
  </ol>
  
  <p>I need a pure SQL code to insert data into <code>table 5</code> from <code>table 1,2,3,4</code> such that:</p>
  
  <ul>
  <li><code>AttendanceDetail</code> has <code>EmpID=100</code>, and <code>Table 2,3,4</code> match the <code>AttenID</code> of <code>AttendanceDetail</code> as for <code>EmpID=100</code>. </li>
  </ul>
  
  <p>I tried it with a cursor and looping but couldn't get what I wish, it is inserting more records than I wish. Please Help Me. Thanks in Advance</p>
  
  <p>OfficeOut and OfficeIn should be inserted from 3 tables A_OfficialDetail,A_recessdetail and A_PersonalDetail According to AttenID in AttendanceDetail. The main purpose is to insert data of Official Out-in,Recess Out-in and Personal Out-in in on Atten_Temp_AttenDetail Table. The table should actually look like:</p>
  
  <pre><code>==================================
  UserID  AttenID  Date      Remark   OfficeOut  OficeIN
  
  100      12      7/8/2011  Office   11:00       12:00
  
  100      12      7/8/2011  Office   13:45        14:00
  </code></pre>
  
  <p>The code I tried is </p>
  
  <pre><code>Declare @AttenID bigint
  
  Open cur
  
  Fetch Next from cur into @AttenID
  
  while @@fetch_status=0
  
  begin
  
  insert into Atten_Temp_AttenDetail(userID,AttenID,Date,OfficeOut,OfficeIn)
  select @AttenID,A.workingDate,OfficeOut,OfficeIn from A_OfficialDetail as O,AttendanceDetail as A where O.AttenID=@AttenID and A.AttenID=@AttenID
  
  insert into Atten_Temp_AttenDetail(userID,AttenID,Date,OfficeOut,OfficeIn)
  select @AttenID,A.workingDate,OfficeOut,OfficeIn from A_PersonalDetail as O,AttendanceDetail as A where O.AttenID=@AttenID and A.AttenID=@AttenID
  
  
  fetch next from cur into @AttenID
  
  end
  
  close cur
  
  Deallocate cur
  </code></pre>