The first year of SQL Server is 1900.

Source: Internet
Author: User

How can I use SQL statements to calculate the first day of this month?

You can write as follows:

SELECT DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0);

According to the datediff definition of the date function, the second parameter is the start date and the third parameter is the end date. What does 0 mean here?

It seems that the date type is essentially a numerical value, so there is no error in writing 0 here. The question is, on which day is 0?

SELECT CAST(0 AS DATETIME)

The result is: 00:00:00. 000.

It turns out that 0 is the first year of SQL Server. Therefore,

SELECT DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0);

That is, first obtain the month from the first year of the month, and then use the first year + the month to get the date, that is, the first day of the month.

Similarly, Monday of this week is

SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()),0);

To be more complex, How about Monday of the first week of this month?

-- Declare @ firstday datetime = dateadd (mm, datediff (mm, 0, getdate (), 0) on the first day of this month; -- declare @ sevenday datetime = dateadd (DD, 6, @ firstday); -- select dateadd (wk, datediff (wk, 0, @ sevenday );

Why is it 7th days?

If the first day of this month is Monday, the second day is Sunday, which is the same week;

For example, if the first day of this month is Sunday, the first day is Saturday, which spans one week. The first day of this month is the week of the first day;

Both extreme situations are taken into consideration. The others are more clear, that is, the Monday of the first week of this month must be in the week of the first day of this month.

Related Article

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.