SQL DECLARE and SET datetime
This article discusses the DECLARE statement in SQL, which you can find the official documentation here: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql?view=sql-server-2017
The DECLARE statement is used in a SQL statement to declare a variable. The declared variable can then be set using SET statement. Once set, the declared variable can be referred by the SELECT statement.
The DECLARE statement can also be used to declare a DATETIME and the SET statement can modify this DATETIME with DATEADD. This allows us to avoid dealing with JavaScript datetime variables.
For our case, we wanted to query all individuals that were set to turn 18 years old within a year.
In order to do this, we first ‘DECLARE’d the variables we would need and modified them using SET:
Note: First argument of DATEADD function can be any accepted SQL interval (year,month,week,day,hour,second,etc.)
Now that our 3 variables had been set, we were able to refer to them in the WHERE portion of the SELECT statement:
Full query with results:
By specifying the search range using DECLARE and SET, we are able to query the DOBs of just those users that are set to turn 18 years of age within a year of the query date.