sql >> Database >  >> RDS >> Sqlserver

Hoe DATEDIFF gebruiken om jaar, maand en dag terug te geven?

Maak deze functie, het geeft een exact datumverschil zoals jaar maanden dagen

    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


  1. Zoekresultaat niet geretourneerd zoals verwacht

  2. Voeg twee queries samen in Mysql

  3. SQL Query Selecteer eerste rang 1 rij Van Meerdere rangen/Groep

  4. Hoe json-array filteren op elke geretourneerde rij?