The function of SQL server to calculate age must be rigorous, and it needs to take into account the situation that the birthday is in a leap year

For the calculation of age, it is necessary to take into account the situation of leap years and perform special treatment, mainly because the existence of leap years will cause some problems caused by birthdays. Specifically, for calculating age, you need to pay attention to the following two issues:

For the case where the birthday is February 29, since there is no such day in a non-leap year, special handling is required when calculating the number of days in the month of the birthday. The existence of leap year will affect the calculation of the number of days from the birthday and the whole year.
When calculating the difference of the whole year, special treatment is required for the situation that spans the leap year. Since the number of days in different years is different, the existence of the leap year will lead to inaccurate calculation of the number of days.

When dealing with the above two problems, the influence of leap year needs to be considered, otherwise it will lead to inaccurate calculations, especially in the case of crossing the year and calculating the number of days in the birthday month. Therefore, special handling is required to ensure the accuracy of calculating age.

CREATE FUNCTION [dbo].[GetAge] (@birthday DATE, @today DATE)
RETURNS INT
AS
BEGIN
    DECLARE @age INT
    SET @age = DATEDIFF(YEAR, @birthday, @today) - CASE
        -- if today's date falls within this year If there is no birthday before your birthday, age minus one
        WHEN MONTH(@birthday) * 100 + DAY(@birthday) > MONTH(@today) * 100 + DAY(@today) THEN 1
        -- if this year's birthday is 2 March 29th, but this year is not a lunar year, the birthday needs to be adjusted to March 1st
        WHEN MONTH(@birthday) = 2 AND DAY(@birthday) = 29 AND
             (DATEDIFF(DAY, @birthday, @today) < DATEDIFF(DAY , '1904-02-29', @today) - DATEDIFF(DAY, '1904-02-29', @birthday) OR
              DATEDIFF(DAY, @birthday, @today) = DATEDIFF(DAY, '1904-02-29', @today) - DATEDIFF(DAY, '1904-02-29', @birthday) AND DATEPART(YEAR, @today) % 4 <> 0) THEN 1
        ELSE 0 END
    RETURN @age
END

When this function calculates the age, it first uses the T-SQL function  DATEDIFF to compare the difference in the entire year between the two dates, and then calculates the age accurately based on multiple factors such as adjusting the birthday and whether or not the year is adjourned.

Example usage:

SELECT [dbo].[GetAge]('2000-02-29', '2024-03-01');

This SQL statement will return the integer value 24, which means that the calculation ends on March 1, 2024, and the age of the person whose birthday is February 29, 2000 is 24 years old.

Guess you like

Origin blog.csdn.net/qq1507171150/article/details/131189071