简体   繁体   English

将基于其他列的计算的列添加到 SQL Server 中的现有表

[英]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:我的问题是如何适应我想要成为表格中新 AGE 列的内容,该列是根据我得到的出生日期计算的,如下所示:

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

How does this work in SQL ?这在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SQL Server 2000-根据其他3列的值从4列表返回单个列值 - SQL Server 2000 - Returning a single column value from a 4 column table based on the values of the other 3 columns 如何根据条件向现有的 SQL 服务器表添加列? - How to add column to an existing SQL Server table based on condition? 根据选择 SQL Server 上其他列的条件添加计算列 - Add calculated columns based on conditions of other column on select SQL Server SQL - 如何根据其他列的值添加计算列 - SQL - How to add a calculated column based on values from other columns SQL Server:根据其他2列中的条件更新boolean列 - SQL Server : update boolean column based on conditions from 2 other columns SQL Server - 如果存在于其他表中,则更改列? - SQL Server - change column if existing in other table? 根据 SQL Server 中其他表中的值更新多个列 - Update multiple columns based on values from other table in SQL Server 使用 SQL 服务器中的现有数据向表中添加列 - Add column to table with existing data in SQL Server 将列添加到现有SQL Server表 - 含义 - Add column to existing SQL Server table - Implications 为什么我不能使用引用 SQL 中其他列的 checkConstraint 将列添加到现有表 - Why can't I add a column to an existing table with a checkConstraint that references other columns in SQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM