I think you can simplify it to just this:selectRTC.shift_times,RTC.shift_times_2,RTC.time_1,case when RTC.time_1 = '' then null when RTC.shift_times = '' then null else datediff(hour, cast(RTC.shift_times as datetime), cast(RTC.time_1 as datetime) + case when RTC.shift_times > RTC.time_1 then 1 else 0 end) end As Hours_OnDuty2 from ( select shift_times = '19:00', shift_times_2 = '07:00', time_1 = '06:00' ) as RTC
Edit: added bolding to highlight the new code.