tsql: How to retrieve the last date of each month between given date range

前端 未结 9 1808
深忆病人
深忆病人 2020-12-06 22:00

I have two date for example 08/08/2013 and 11/11/2013 and I need last date of each month starting from August to November in a table so that i can iterate over the table to

9条回答
  •  隐瞒了意图╮
    2020-12-06 22:15

    Following script demonstrates the script to find last day of previous, current and next month.

    ----Last Day of Previous Month
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
    LastDay_PreviousMonth
    ----Last Day of Current Month
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
    LastDay_CurrentMonth
    ----Last Day of Next Month
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
    LastDay_NextMonth
    

    If you want to find last day of month of any day specified use following script.

    --Last Day of Any Month and Year
    DECLARE @dtDate DATETIME
    SET @dtDate = '8/18/2007'
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
    LastDay_AnyMonth
    ResultSet:
    LastDay_AnyMonth
    

    Source - SQL Server Central.

提交回复
热议问题