SQL Query to find the last day of the month

前端 未结 14 1550
太阳男子
太阳男子 2020-11-27 04:40

I need to find the last day of a month in the following format:

\"2013-05-31 00:00:00:000\"

Anybody please help out.

相关标签:
14条回答
  • 2020-11-27 05:06
    declare @date datetime;
    set @date = getdate(); -- or some date
    select dateadd(month,1+datediff(month,0,@date),-1);
    
    0 讨论(0)
  • 2020-11-27 05:07

    SQL Server 2012 introduces the eomonth function:

    select eomonth('2013-05-31 00:00:00:000')
    -->
    2013-05-31
    
    0 讨论(0)
  • 2020-11-27 05:11
    TO FIND 1ST and Last day of the Previous, Current and Next Month in Oracle SQL
    -----------------------------------------------------------------------------
    SELECT 
    SYSDATE,
    LAST_DAY(ADD_MONTHS(SYSDATE,-2))+1 FDPM,
    LAST_DAY(ADD_MONTHS(SYSDATE,-1)) LDPM,
    LAST_DAY(ADD_MONTHS(SYSDATE,-1))+1 FDCM,
    LAST_DAY(SYSDATE)LDCM,
    LAST_DAY(SYSDATE)+1 FDNM,
    LAST_DAY(LAST_DAY(SYSDATE)+1) LDNM
    FROM DUAL
    
    0 讨论(0)
  • 2020-11-27 05:12

    I know this question was for SQL Server 2005, but I thought I'd mention- as of SQL 2012, there now is an EOMONTH() function that gets the last day of the month. To get it in the format specified by the original asker you'd have to cast to a datetime.

    SELECT CAST(eomonth(GETDATE()) AS datetime)
    
    0 讨论(0)
  • 2020-11-27 05:13

    Just a different version of adding a month and subtracting a day for creating reports:

    ex: StartofMonth is '2019-10-01'

    dateadd(day,-1,dateadd(month,1,StartofMonth))

    EndOfMonth will become '2019-10-31'

    0 讨论(0)
  • 2020-11-27 05:15

    Try this one -

    CREATE FUNCTION [dbo].[udf_GetLastDayOfMonth] 
    (
        @Date DATETIME
    )
    RETURNS DATETIME
    AS
    BEGIN
    
        RETURN DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @Date) + 1, 0))
    
    END
    

    Query:

    DECLARE @date DATETIME
    SELECT @date = '2013-05-31 15:04:10.027'
    
    SELECT DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @date) + 1, 0))
    

    Output:

    -----------------------
    2013-05-31 00:00:00.000
    
    0 讨论(0)
提交回复
热议问题