Get the last day of the month in SQL

后端 未结 20 2028
借酒劲吻你
借酒劲吻你 2020-11-27 04:49

I need to get the last day of the month given as a date in SQL. If I have the first day of the month, I can do something like this:

DATEADD(DAY, DATEADD(MONT         


        
相关标签:
20条回答
  • 2020-11-27 05:02

    For SQL server 2012 or above use EOMONTH to get the last date of month

    SQL query to display end date of current month

    DECLARE @currentDate DATE = GETDATE()
    SELECT EOMONTH (@currentDate) AS CurrentMonthED
    

    SQL query to display end date of Next month

    DECLARE @currentDate DATE = GETDATE()
    SELECT EOMONTH (@currentDate, 1 ) AS NextMonthED
    
    0 讨论(0)
  • 2020-11-27 05:03

    This query can also be used.

    DECLARE @SelectedDate DATE =  GETDATE()
    
    SELECT DATEADD(DAY, - DAY(@SelectedDate), DATEADD(MONTH, 1 , @SelectedDate)) EndOfMonth
    
    0 讨论(0)
  • 2020-11-27 05:04
    ---Start/End of previous Month 
    Declare @StartDate datetime, @EndDate datetime
    
    set @StartDate = DATEADD(month, DATEDIFF(month, 0, GETDATE())-1,0) 
    set @EndDate = EOMONTH (DATEADD(month, DATEDIFF(month, 0, GETDATE())-1,0)) 
    
    SELECT @StartDate,@EndDate
    
    0 讨论(0)
  • 2020-11-27 05:05

    Take some base date which is the 31st of some month e.g. '20011231'. Then use the
    following procedure (I have given 3 identical examples below, only the @dt value differs).

    declare @dt datetime;
    
    set @dt = '20140312'
    
    SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
    
    
    
    set @dt = '20140208'
    
    SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
    
    
    
    set @dt = '20140405'
    
    SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
    
    0 讨论(0)
  • 2020-11-27 05:06

    This works for me, using Microsoft SQL Server 2005:

    DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,'2009-05-01')+1,0))
    
    0 讨论(0)
  • 2020-11-27 05:08

    From SQL Server 2012 you can use the EOMONTH function.

    Returns the last day of the month that contains the specified date, with an optional offset.

    Syntax

    EOMONTH ( start_date [, month_to_add ] ) 
    

    How ... I can find the last day of the month for any given date?

    SELECT EOMONTH(@SomeGivenDate)
    
    0 讨论(0)
提交回复
热议问题