Obtain the first day of the month of the specified date in mssql.

Source: Internet
Author: User

Obtain the first day of the specified date month. You can use the DATEADD function to subtract the number of days that have elapsed since the month of the specified date.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
Return cast (DATEADD (day, 1-DAY (@ Date), @ Date) as datetime)
END

Alternatively, use DATEDIFF to calculate the number of months between the specified date and the start of the date, and then add DATEADD to the number of months, starting from scratch.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
Return dateadd (MONTH, DATEDIFF (MONTH, 0, @ Date), 0)
END

Alternatively, extract the year or month from the specified date and combine it with 01 to get the first day of the specified date.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ y NVARCHAR (4) = CAST (YEAR (@ Date) as nvarchar (4 ))
DECLARE @ m NVARCHAR (2) = CAST (MONTH (@ Date) as nvarchar (2 ))
Return cast (@ y + N'-'+ @ m + N'-01') as datetime)
END

Alternatively, refer to this article: The http://www.jb51.net/article/23285.htm uses the CONVERT function to specify the date format for conversion, which also gets the first day of the month of the specified date.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ ym NVARCHAR (10) = CONVERT (varchar (8), GETDATE (), 23)
Return cast (@ ym + n'01') as datetime)
END

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.