sql >> Base de Datos >  >> RDS >> Sqlserver

¿Cómo usar DATEDIFF para devolver año, mes y día?

Cree esta función, dará la diferencia de fecha exacta como año meses días

    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 @[email protected]
     set @[email protected]
     set @[email protected]
     end



    SELECT @month=datediff (MONTH,@date,@date2)

    if dateadd(month,@month,@date) >@date2
    begin
    set @[email protected]
    end
    set @day=DATEDIFF(day,dateadd(month,@month,@date),@date2)

    set @[email protected]/12
    set @[email protected] % 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