Your comparison will work, but it will be slow because the dates are converted to a string for each row. To effectively compare two parts of the time, try:
declare @first datetime set @first = '2009-04-30 19:47:16.123' declare @second datetime set @second = '2009-04-10 19:47:16.123' select (cast(@first as float) - floor(cast(@first as float))) - (cast(@second as float) - floor(cast(@second as float))) as Difference
Long explanation: the date on the SQL server is stored as a floating point number. The digits before the decimal point represent the date. The numbers after the decimal point represent time.
So here is an example of a date:
declare @mydate datetime set @mydate = '2009-04-30 19:47:16.123'
Let me convert it to float:
declare @myfloat float set @myfloat = cast(@mydate as float) select @myfloat
Now take the part after the number, i.e. time:
set @myfloat = @myfloat - floor(@myfloat) select @myfloat -- Shows 0,824492168212601
Convert it back to datetime:
declare @mytime datetime set @mytime = convert(datetime,@myfloat) select @mytime -- Shows 1900-01-01 19:47:16.123
1900-01-01 is only a โzeroโ date; you can display the temporary part with convert, specifying, for example, format 108, which is only time:
select convert(varchar(32),@mytime,108)
Conversions between datetime and float are pretty fast, because they are basically stored the same way.
Andomar Apr 30 '09 at 18:55 2009-04-30 18:55
source share