How to use DATEDIFF to return year, month and day?

后端 未结 9 916
离开以前
离开以前 2020-12-10 22:36

How can I use DATEDIFF to return the difference between two dates in years, months and days in SQL Server 2005

DATEDIFF (date , dat         


        
9条回答
  •  轮回少年
    2020-12-10 23:19

    Create this function, it will give exact date difference like year months days

        Create function get_Exact_Date_diff(@date smalldatetime,@date2 smalldatetime)
     returns varchar(50)
    
        as
    
        begin
    
        declare @date3 smalldatetime
    
        Declare @month int,@year int,@day int
    
         if @date>@date2
         begin
         set @date3=@date2
         set @date2=@date
         set @date=@date3
         end
    
    
    
        SELECT @month=datediff (MONTH,@date,@date2)
    
        if dateadd(month,@month,@date) >@date2
        begin
        set @month=@month-1
        end
        set @day=DATEDIFF(day,dateadd(month,@month,@date),@date2)
    
        set @year=@month/12
        set @month=@month % 12
    
        return (case when @year=0 then '' when @year=1 then convert(varchar(50),@year ) + ' year ' when @year>1 then convert(varchar(50),@year ) + ' years ' end)
        + (case when @month=0 then '' when @month=1 then convert(varchar(50),@month ) + ' month ' when @month>1 then convert(varchar(50),@month ) + ' months ' end)
        + (case when @day=0 then '' when @day=1 then convert(varchar(50),@day ) + ' day ' when @day>1 then convert(varchar(50),@day ) + ' days ' end)
    
        end
    

提交回复
热议问题