I am trying to write a function where I can find age based on the date the record was inserted rather than getdate(). I want to filter the user who are less than 18 years when they registered. If I query it after a year, it should still show the user as 17 based on record insert date than current date. This is what I wrote but it is still giving the age based on current date than the record insert date. Any suggestions would be really helpful. Thank You
--InputDate as DateOfBirth
--InsertDate as date the record was inserted
CREATE FUNCTION [dbo].[FindAge] (@InputDate int, @Insertdate datetime )
RETURNS int
AS
BEGIN
DECLARE @Age as Int
DECLARE @d DATETIME
SET @d = CONVERT(DATETIME, CONVERT(VARCHAR(8), @InputDate), 112)
SELECT @Age=DATEDIFF(year, @d, @Insertdate)
- CASE WHEN DATEADD(year, DATEDIFF(year, @d, @Insertdate), @d) <= GetDate()
THEN 0 ELSE 1 END
RETURN @Age
END
---- Drop Obselete procs
GO
Update Followed Bacon Bits suggestion and it worked out perfectly.