简体   繁体   中英

Add a column based on calculation from other columns to an existing table in SQL Server

I know how to add a column in a table via the following code

ALTER TABLE {TABLENAME} 
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} 
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES

My question is how to fit in what I want to be the new AGE column in my table which is calculated based on the birth dates I got which looks like this:

to_number((CURRENT_DATE()-to_date(date_of_birth,'dd/mm/yyyy'))/365)

How does this work in SQL ?

Why don't you create a view for this table, and add this expression as a column to your view?

create table friends (id number, name varchar, date_of_birth varchar);

insert into friends values ( 1, 'Gokhan', '01/01/1980');

create view friends_v as select id, name, date_of_birth, to_number((CURRENT_DATE()-to_date(date_of_birth,'dd/mm/yyyy'))/365) as age from friends;

select * from friends_v;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM