Calculating Age using Date of Birth and Current Date

sid78669

This code demonstrates how age might be calculated and filtered using the DateDiff method in SQL. Also, note that both the parameters are set to NULL by default, hence making them 'optional' to a certain limit.

352 Views
About the Author

I might be a geeky person, but I love to play actual sports, i.e. Soccer and Swimming and Hockey more than computer games. My favorite thing to do, for pleasure, is go on long 6-10 hour drives! Computers were a hobby till i figured it would be easier for me to get good grades and maintain a wonderful GPA in University, which in turn made me switch from Political Science to Computers Science ;)

Create PROCEDURE [dbo].[pr_AgeFiltering]
	(
		@ageFrom int = NULL,
		@ageTo int = NULL
	)

AS
	DECLARE @sql varchar(2000)
	SELECT @sql = 'SELECT CONVERT(VARCHAR, [User].USER_NAME, 120) AS NAME, CONVERT(VARCHAR, [User].DOB, 120) AS DOB, (DATEDIFF(dd, [User].DOB, GetDate())  / 365) AS Age FROM [User] WHERE 1=1 '
	
-- Set the Lower limit for age (optional)
	IF ( @ageFrom IS NOT NULL AND @ageFrom > 0 ) 
		SELECT @sql = @sql + ' AND (DATEDIFF(dd, [User].DOB, GetDate())  / 365) > = ' + CONVERT(varchar(10),@ageFrom)

--Set the upper limit for age (optional)
	IF ( @ageTo IS NOT NULL AND @ageTo > 0 )
		SELECT @sql = @sql + ' AND (DATEDIFF(dd, [User].DOB, GetDate())  / 365) < = ' + CONVERT(varchar(10),@ageTo
	
--Execute the SQL query
EXEC(@sql)

	RETURN