Created
August 19, 2014 04:16
-
-
Save kiwipiet/2e9ef7d444028355fd4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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