-- Collection of code snippets by Arne Vajhøj 
-- posted to eksperten.dk, usenet and other places (2002-now) 
CREATE FUNCTION udf_age(@birthday_string CHAR(10)) RETURNS INTEGER
AS
BEGIN
    DECLARE @birthday AS DATETIME
    IF CONVERT(INTEGER, '20' + SUBSTRING(@birthday_string,5,2)) <= YEAR(GETDATE())
        SET @birthday = CONVERT(DATETIME, '20'+SUBSTRING(@birthday_string,5,2)+SUBSTRING(@birthday_string,3,2)+SUBSTRING(@birthday_string,1,2), 112)
    ELSE
        SET @birthday = CONVERT(DATETIME, '19'+SUBSTRING(@birthday_string,5,2)+SUBSTRING(@birthday_string,3,2)+SUBSTRING(@birthday_string,1,2), 112)
    RETURN YEAR(GETDATE())-YEAR(@birthday)-CASE WHEN DATEPART(dy,GETDATE())<DATEPART(dy,@birthday) THEN 1 ELSE 0 END
END
GO
SELECT dbo.udf_age('1401680123')
GO
SELECT dbo.udf_age('1501680123')
GO
SELECT dbo.udf_age('1601680123')
GO
SELECT dbo.udf_age('1501070123')
GO
DROP FUNCTION udf_age
GO
