1. 程式人生 > >SQL通過出生日期獲取年齡

SQL通過出生日期獲取年齡

IF EXISTS(SELECT 1 FROM sysobjects WHERE [name] = 'GetAge')
    DROP FUNCTION dbo.GetAge
go
CREATE FUNCTION dbo.GetAge
(
    @birthday DATETIME
)
RETURNS INT
AS
BEGIN
    IF(@birthday IS NOT NULL AND ISDATE(@birthday) = 1)
        BEGIN
            DECLARE @age INT , @y INT , @m INT , @d INT , @now DATETIME
            SET @now = GETDATE()
            SET @y = DATEPART(YEAR,@now) - DATEPART(YEAR,@birthday)
            SET @m = DATEPART(MONTH,@now) - DATEPART(MONTH,@birthday)
            SET @d = DATEPART(DAY,@now) - DATEPART(DAY,@birthday)
            IF(@m = 0 AND @d = 0)
                BEGIN
                    SET @age = @y
                END
            ELSE
                BEGIN
                    IF @m > 0 OR (@m = 0 AND @d > 0)
                        SET @age = @y
                    ELSE
                        SET @age = @y - 1
                END
            IF @age < 0 SET @age = 0
        END
    ELSE
        BEGIN
            SET @age = NULL
        END
    RETURN @age
END