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

后端 未结 9 932
离开以前
离开以前 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:32

    Using ParseName
    
    DECLARE
      @ReportBeginDate DATE
    
    SET @ReportBeginDate='2015-01-01';
    
    IF OBJECT_ID('TEMPDB..#tmp_ymd') IS NOT NULL
    BEGIN
    DROP TABLE #tmp_ymd;
    END;
    
    select
    cast(cast(datediff(mm,@ReportBeginDate,getdate()) as decimal (10,2))/12 as decimal(10,2)) as YearMonthDec
    ,cast(datediff(dd,@ReportBeginDate,getdate()) as decimal (10,2)) as DayDec
    into #tmp_ymd
    
    select
    YearMonthDec
    ,cast(parsename(YearMonthDec,2) as decimal (10,0)) as yearnum
    ,cast(cast(parsename(YearMonthDec,1) as decimal (10,0))/100*(12) as numeric) as monthnum
    ,case when YearMonthDec>=1 then datediff(dd,CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(getdate())-1),getdate()),101),getdate()) else DayDec end as daynum
    
    from #tmp_ymd
    

提交回复
热议问题