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.
Calculating Age using Date of Birth and Current Date
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
Be a part of the DaniWeb community
We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.