Skip to content

Instantly share code, notes, and snippets.

@kiwipiet
Created August 19, 2014 04:16
Show Gist options
  • Save kiwipiet/2e9ef7d444028355fd4d to your computer and use it in GitHub Desktop.
Save kiwipiet/2e9ef7d444028355fd4d to your computer and use it in GitHub Desktop.
CREATE FUNCTION [dbo].[GetAge] (
@DOB AS DATE
,@EndDate AS DATE = NULL
)
RETURNS TINYINT
AS
BEGIN
DECLARE @Result AS TINYINT
IF (@EndDate IS NULL)
SET @EndDate = CAST(GETDATE() AS DATE)
IF (@DOB >= @EndDate) -- trap errors
SET @Result = 0
ELSE
BEGIN
-- check if the person had its birthday in the specified year and calculate age
IF (MONTH(@EndDate) * 100) + DAY(@EndDate) >= (MONTH(@DOB) * 100) + DAY(@DOB)
SET @Result = CAST(DATEDIFF(Year, @DOB, @EndDate) AS TINYINT)
ELSE
SET @Result = CAST(DATEDIFF(Year, @DOB, @EndDate) - 1 AS TINYINT)
END
RETURN @Result
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment