Obtain the number of days in the month by SQL.

Source: Internet
Author: User
Tags getdate

The number of days in a month for SQL query. The following describes several methods for obtaining day data and processing of special months in January.

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

SQL SERVER 2005 obtains the number of days in the current month
SQL code

1. SELECT 32-DAY (getdate () + 32-DAY (getdate ()))
SELECT 32-DAY (getdate () + 32-DAY (getdate ()))

Special handling of January

You need to input a year to obtain the number of days of the year in January. Can be written as a user-defined function

Create function [dbo]. [DaysOfFebruary]
    (
@ Year INT
    )
RETURNS INT
AS
BEGIN
Return case when (@ Year % 4 = 0 AND @ Year % 100 <> 0) OR (@ Year % 400 = 0) THEN 29 ELSE 28 END
END

Instance

SELECT [dbo]. [DaysOfFebruary] (2011)

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.