添加非空列从其他列取值

add not null column take values from other column

我有一个现有的 table 说,ItemsId | CreateDate(作为 DateTime)列;要添加 Year int not null,从 CreateDate 列中获取默认年份。

Year 值以后会更新为不同的值,但在添加 Year 列时只需将其设置为默认值,因为要向 Year 添加不可为 null 的列。

这可能吗?

不要为其他列操心——除非您觉得将来需要更改该列的值。相反,只需使用计算列:

alter table t add created_year as (year(created_date));

这是在您查询 table 时自动计算的,因此它始终准确,无论是新行还是旧行。

据推测,created_date 永远不会更新。

如果您想添加一个新列并使用另一列的值对其进行初始化,您可以这样做:

-- add the column (as nullable)
alter table mytable add created_year int;

-- update the values on existing rows
update items set created_year = year(created_date);

-- make the column not nullable
alter table mytable alter column created_year int not null;