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