How to obtain the number of days of a month in sqlserver

Source: Internet
Author: User

As follows: Copy codeThe Code is as follows: create function [dbo]. [udf_DaysInMonth]
(
@ Date DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @ dim as table (m int, Dy INT)
Insert into @ dim VALUES
),
),
(2,
Case when (YEAR (@ Date) % 4 = 0 and year (@ Date) % 100 <> 0) OR (YEAR (@ Date) % 400 = 0)
THEN 29
ELSE 28 END
)
DECLARE @ RValue INT
SELECT @ RValue = [Dy] FROM @ dim WHERE [M] = MONTH (@ Date)
RETURN @ RValue
END
GO

Obtain the number of days of the month, which has been written on the blog before, but it is only the number of days of the month. Link: http://www.cnblogs.com/insus/articles/2025019.html
Seeing this function in the project at first glance, I always feel that it is not well written and whether it can be rewritten better, the inspiration is also from the CASE function that gets the number of days in January.
Therefore, I tried to change it as follows:Copy codeThe Code is as follows: create function [dbo]. [udf_DaysInMonth]
(
@ Date DATETIME
)
RETURNS INT
AS
BEGIN
Return case when month (@ Date) IN (1, 3, 5, 7, 8, 10, 12) THEN 31
When month (@ Date) IN (4, 6, 9, 11) THEN 30
Else case when (YEAR (@ Date) % 4 = 0 and year (@ Date) % 100 <> 0) OR (YEAR (@ Date) % 400 = 0)
THEN 29
ELSE 28
END
END
END

If you have referenced the custom function Insus. NET that obtains the number of days in January, you can also refer to the following version:Copy codeThe Code is as follows: create function [dbo]. [udf_DaysInMonth]
(
@ Date DATETIME
)
RETURNS INT
AS
BEGIN
Return case when month (@ Date) IN (1, 3, 5, 7, 8, 10, 12) THEN 31
When month (@ Date) IN (4, 6, 9, 11) THEN 30
ELSE [dbo]. [DaysOfFebruary] (YEAR (@ Date ))
END
END

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.