0

I have to check if a user is old enough. I tried as shown here, but this only works for years.

So, for example 11/7/2003 should be true but 12/12/2003 should be false. But, with my code each of these is true.

Here is my code:

[birthdate]date CHECK(DATEDIFF(year,birthdate,getdate()) >= 18),

How can I write this in another way that the months and days will matter?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
  • 1
    Aside comment: `SSMS` is the user interface that many of us use to interact with SQL Server. The database engine, SQL Server, is relevant to coding questions. The interface is not. – Eric Brandt Nov 09 '21 at 14:14
  • 1
    FYI, `DATEDIFF(year,birthdate,getdate())` is not a good way to determine someone's age. People are born on days other than 01 January. – Larnu Nov 09 '21 at 14:23
  • Does this answer your question? [How to calculate age (in years) based on Date of Birth and getDate()](https://stackoverflow.com/questions/1572110/how-to-calculate-age-in-years-based-on-date-of-birth-and-getdate) – Ali Fidanli Nov 09 '21 at 14:27

3 Answers3

2

Instead of doing arithmetic on the column and checking the result, do arithmetic on GETDATE and do a normal comparison

[birthdate]date CHECK(birthdate <= DATEADD(year, -18, getdate())),

This is good practice in any case for WHERE and JOIN predicates, as it means indexes can be used.

Charlieface
  • 29,562
  • 5
  • 12
  • 30
0

Want to find people who are at least 18, given then date of birth?

SELECT Cast(CURRENT_TIMESTAMP AS date) AS today
     , DateAdd(yy, -18, Cast(CURRENT_TIMESTAMP AS date)) AS eighteen_years_ago
;

Anyone born on or before eighteen_years_ago is at least 18 years old.

gvee
  • 16,080
  • 30
  • 47
-1

Check the number of days from date A to B and replace the condition with >= 6570 (365*18).

This method does not check for leap years.

Larnu
  • 76,706
  • 10
  • 34
  • 63
Megafry
  • 74
  • 1
  • 5