Skip to content
Advertisement

If the age is older than 18, then save the Customer record

I want to create a function, which checks the age from by the entry a record. if the age is older than 18, then save the record. If not, don’t save the record.

Thanks a lot for your kind help.

Advertisement

Answer

The question really is about how to compute an age from a date of birth in SQL Server. It is not that easy, since there is no built-in for that, and because functions such as datediff() cannot really give an accurate results (or at least not without many convolutions).

A simple and efficient method is to convert the date of birth and the current date to format YYYYMMDD, turn that to a string, then use simple arithmetics, like so:

In your function:

I slightly modified the original code so it compiles properly, and returns the computed date as well (which makes it easy to debug).

Now we can test:

dob        | res                 
:--------- | :-------------------
2000-01-01 | Age verified: 20    
2002-06-11 | Age verified: 18    
2002-06-13 | Age not verified: 17
2010-01-01 | Age not verified: 10
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement