I’m trying to calculate the age of a user based on the current year and his year of birth, but something in my syntax appears to be incorrect and I can’t spot it.
CREATE TABLE Normal_Users( first_name varchar(20), last_name varchar(20), date_of_birth date, age int = year(CURRENT_TIMESTAMP) - year(date_of_birth) )
Why is this incorrect?
Advertisement
Answer
Use AS:
CREATE TABLE Normal_Users( first_name varchar(20), last_name varchar(20), date_of_birth date, age int AS (year(CURRENT_TIMESTAMP) - year(date_of_birth)) );
< type> [ GENERATED ALWAYS ] AS ( < expression> ) [ VIRTUAL|STORED ] [ UNIQUE [KEY] ] [ [PRIMARY] KEY ] [ NOT NULL ]
[ COMMENT ]
If you are using SQL Server there is no need for datatype in computed columns:
CREATE TABLE Normal_Users(
first_name varchar(20),
last_name varchar(20),
date_of_birth date,
age AS (year(CURRENT_TIMESTAMP) - year(date_of_birth))
);
EDIT:
For calculating age better use:
SELECT TIMESTAMPDIFF( YEAR, date_of_birth, CURDATE()) AS age;
Your code for 2014-12-31 and 2015-01-01 will return 1 year, but really it has 0.