The first part combines #Trans and #Employee with UNION ALL . But since you still need to distinguish between two, to make
t1.over_time = t1.over_time --<------------- One is cumalative add and the other isn't + CAST(RIGHT('0'+ CAST(overtimeHours as varchar(2)),2) +':00:00' As Time) + CAST(RIGHT('0'+ CAST(@total_min as varchar(2)),2) +':00:00' As Time),
for trans and
t1.over_time = CAST(RIGHT('0'+ CAST(overtimeHours as varchar(2)), 2) +':00:00' As Time) + CAST(RIGHT('0'+ CAST(@total_min as varchar(2)),2) +':00:00' As Time),
for Employee, I add an EmployeeType column to the CTE. In addition, some assumptions were made regarding the type of destination data in the rr_datatype table. If this is essentially TIME or DATETIME or some other option, you should use the DATEADD function. MSDN page here ..
And finally, the second UPDATE can also be combined into the first if you are only going to update the records participating in the first UPDATE and are not trying to update the entire table.
; WITH TransAndEmployee AS ( SELECT 'T' AS EmployeeType, dayDate, shiftName, limit FROM #ShiftTrans UNION ALL SELECT 'E' AS EmployeeType, dayDate, shiftName, limit FROM #ShiftEmployees ), PoundOvertime AS ( SELECT * FROM TransAndEmployee a RIGHT OUTER JOIN #ResidenceOvertime b ON a.dayDate = b.dayDate INNER JOIN ShiftDetails c ON c.shiftId = a.shiftId AND c.shiftTypeId = b.shiftTypeId; ) UPDATE ot SET over_time = DATEADD(mi,@total_min, DATEADD(hh,overtimeHours,CASE WHEN EmployeeType = 'T' THEN over_time ELSE '0:00' END) ), day_flag = day_flag + 'R1', day_desc = 'R::' + CTE_Residence_Overtime_trans.shiftName + '[ ' + CTE_Residence_Overtime_trans.name + ' ]' FROM rr_overtime ot INNER JOIN PoundOvertime p ON ot.[trans_date] = p.[dayDate] WHERE ot.emp_num = @empNum UPDATE rr_overtime SET over_time = CAST('00:00:00' As Time), -- You can probably do over_time = '00:00' if over_time is TIME day_flag = day_flag +'R2' WHERE trans_date = @TomorrowDate AND emp_num = @empNum;
Another assumption I made ... below seemed a bit odd to me. I assumed that you were trying to add βminutesβ ... however this line of manipulation seems to add it to the clock. I βfixedβ this ... let me know if this was a bad guess.
+ CAST(RIGHT('0'+ CAST(@total_min as varchar(2)),2) +':00:00' As Time),