# SQL statement at month end of month (first day, last day of date)

Source: Internet
Author: User

The first day of the month on which the given date is calculated

The trick is to calculate the
number of time intervals between the current date and "1900-01-01" and then add it to "1900-01-01" to get a special date, a technique that can be used---to calculate many different dates.
DECLARE @date datetime
Set @date =getdate ()
Select DATEADD (Month,datediff (month, ' 1900-01-01 ', @date), ' 1900-01-01 ') as ' the first day of the month '
--streamlined algorithm, based on the time representation of SQL Server, "1900-01-01" can be replaced by 0
Select DATEADD (Month,datediff (month,0, @date), 0) as ' the first day of the month '
--The above two algorithms are accurate to the timing of 00:00:00.000
--The following algorithm class to keep time and seconds
--Train of thought: Subtract the number of days from the first day of the month from the given date with a given date
Select DATEADD (Day,1-datepart (Day, @date), @date)
Go

-month end, calculates the last day of the month for the given date

DECLARE @date datetime
Set @date =getdate ()
--Train of thought: Next January 1 in the current month minus 1 days
Select DATEADD (Day,-1,dateadd (Month,1+datediff (month, ' 1900-01-01 ', @date), ' 1900-01-01 ')) as ' The Day of the month '
Select DATEADD (Month,1+datediff (month, ' 1900-01-01 ', @date), ' 1900-01-01 ')-1 as ' The Day of the month '
--1900-01-01 with 0 instead
Select DATEADD (Day,-1,dateadd (Month,1+datediff (month,0, @date), 0)) as ' The Day of the month '
Select DATEADD (Month,1+datediff (month,0, @date), 0)-1 as ' The Day of the month '
--Train of thought: Same as the beginning of the month
Select DATEADD (Month,datediff (month, ' 1989-12-31 ', @date), ' 1989-12-31 ') as ' the Day of the month '
--Streamlined algorithm, ' 1989-12-31 ' with 1 instead
Select DATEADD (Month,datediff (month,-1, @date), -1) as ' The Day of the month '
--The algorithm of keeping time and seconds
Go

Related Keywords:

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.