Difference of two date time in sql server

后端 未结 20 2106
心在旅途
心在旅途 2020-12-01 03:53

Is there any way to take the difference between two datetime in sql server?

For example, my dates are

  1. 2010-01-22 15:29:55.090
20条回答
  •  旧时难觅i
    2020-12-01 04:34

    So this isn't my answer but I just found this while searching around online for a question like this as well. This guy set up a procedure to calculate hours, minutes and seconds. The link and the code:

    --Creating Function
    If OBJECT_ID('UFN_HourMinuteSecond') Is Not Null
    Drop Function dbo.UFN_HourMinuteSecond
    Go
    Exec(
    'Create Function dbo.UFN_HourMinuteSecond
    (
    @StartDateTime DateTime,
    @EndDateTime DateTime
    ) Returns Varchar(10) 
    As
    Begin
    
    Declare @Seconds Int,
    @Minute Int,
    @Hour Int,
    @Elapsed Varchar(10)
    
    Select @Seconds = ABS(DateDiff(SECOND ,@StartDateTime,@EndDateTime))
    
    If @Seconds >= 60 
    Begin
    select @Minute = @Seconds/60
    select @Seconds = @Seconds%60
    
    If @Minute >= 60
    begin
    select @hour = @Minute/60
    select @Minute = @Minute%60
    end
    
    Else
    Goto Final 
    End
    
    Final:
    Select @Hour = Isnull(@Hour,0), @Minute = IsNull(@Minute,0), @Seconds =               IsNull(@Seconds,0)
    select @Elapsed = Cast(@Hour as Varchar) + '':'' + Cast(@Minute as Varchar) + '':'' +     Cast(@Seconds as Varchar)
    
    Return (@Elapsed)
    End'
    )
    

提交回复
热议问题