How to get the number of days of the month in SQL Server sharing _mssql

Source: Internet
Author: User
Tags datetime
As follows:
Copy Code code 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
(1,31), (3,31), (5,31), (7,31), (8,31), (10,31), (12,31),
(4,30), (6,30), (9,30), (11,30),
(2,
Case when (@Date)% 4 = 0 and year (@Date)% <> 0) OR (year (@Date)% 400 = 0)
THEN 29
ELSE End
)
DECLARE @RValue INT
SELECT @RValue = [Dy] from @dim WHERE [M] = MONTH (@Date)
Return @RValue
End
Go

Gets the number of days of the month that was previously written on the blog, but it only takes the number of days in February. Links are as follows: http://www.cnblogs.com/insus/articles/2025019.html
Now the first see the project in this function, always feel it is not good enough to write a feeling, whether it can rewrite it better, the inspiration Point is also from the February days of the case function to recall.
So I tried to change it as follows:
Copy Code code 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 if (@Date)% 4 = 0 and year (@Date)% <> 0) OR (year (@Date)% 400 = 0)
THEN 29
ELSE 28
End
End
End

If you already have a custom function that insus.net for February days, you can also refer to the following version:
Copy Code code 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
when MONTH (@Date) in (4,6,9,11) THEN
ELSE [dbo].[ Daysoffebruary] (Year (@Date))
End
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.