Get the last day of the month in SQL

后端 未结 20 2030
借酒劲吻你
借酒劲吻你 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:15

    My 2 cents:

    select DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(day,(0-(DATEPART(dd,'2008-02-12')-1)),'2008-02-12')))
    

    Raj

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

    You could get the days in the date by using the DAY() function:

    dateadd(day, -1, dateadd(month, 1, dateadd(day, 1 - day(date), date)))
    
    0 讨论(0)
  • 2020-11-27 05:18

    using sql server 2005, this works for me:

    select dateadd(dd,-1,dateadd(mm,datediff(mm,0,YOUR_DATE)+1,0))
    

    Basically, you get the number of months from the beginning of (SQL Server) time for YOUR_DATE. Then add one to it to get the sequence number of the next month. Then you add this number of months to 0 to get a date that is the first day of the next month. From this you then subtract a day to get to the last day of YOUR_DATE.

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

    Based on the most voted answer at below link I came up with the following solution:

     declare  @mydate date= '2020-11-09';
      SELECT DATEADD(month, DATEDIFF(month, 0, @mydate)+1, -1) AS lastOfMonth
    

    link: How can I select the first day of a month in SQL?

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

    Using SQL Server, here is another way to find last day of month :

    SELECT DATEADD(MONTH,1,GETDATE())- day(DATEADD(MONTH,1,GETDATE()))
    
    0 讨论(0)
  • 2020-11-27 05:23

    Based on the statements:

    SELECT DATEADD(MONTH, 1, @x)           -- Add a month to the supplied date @x
    

    and

    SELECT DATEADD(DAY,  0 - DAY(@x), @x)  -- Get last day of month previous to the supplied date @x
    

    how about adding a month to date @x and then retrieving the last day of the month previous to that (i.e. The last day of the month of the supplied date)

    DECLARE @x  DATE = '20-Feb-2012' 
    SELECT DAY(DATEADD(DAY,  0 - DAY(DATEADD(MONTH, 1, @x)), DATEADD(MONTH, 1, @x)))
    

    Note: This was test using SQL Server 2008 R2

    0 讨论(0)
提交回复
热议问题