The last day of the month on which the given date is calculated SQL statement

Source: Internet
Author: User
Tags datetime

DECLARE @date datetime
Set @date =getdate ()
--the first day of the current month minus the day
Select DATEADD (Day,-1,dateadd (Month,datediff (month,0, @date), 0)) as ' last day of last month '
--Another algorithm for the first day of the current month
Select DATEADD (Day,-1,dateadd (Day,1-datepart (Day, @date), @date)) ' Last day of last month '
Select DATEADD (Day,1-datepart (Day, @date), @date)-1 ' last month '
--another algorithm that cannot use the last day of the current month plus one months, because the current month can be 30 days.
--For example, select DATEADD (month,1, ' 2010-06-30 ')--the result is 2010-07-30, not 2010-07-31,
This is also the month-end algorithm using the first day of next month minus 1 days to calculate the reason
--but if the calculation month is 31 days without this problem
--For example, select DATEADD (month,1, ' 2010-05-31 ')--the result is 2010-06-30
-So the following algorithm is correct,-1 means ' 1899-12-31 00:00:00.000 '--select CONVERT (datetime,-1)
Select DATEADD (Month,datediff (month,-1, @date) -1,-1)
--Another current month algorithm
Select DATEADD (Day,-1,dateadd (Day,1-datepart (Day, @date), @date)) ' Last day of last month '
--Simplifying
Select DATEADD (Day,0-datepart, @date), @date) ' Last day of last month '
Go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.