添加非空列从其他列获取值

Ser*_*rge 3 sql t-sql sql-server create-table sql-update

我有一个现有的表,Items其中包含Id | CreateDate(作为日期时间)列;要添加,请从列中获取默认年份。Year int not nullCreateDate

Year值将来会更新为不同的值,但只需在添加“年份”列时将其设置为默认值,因为要向“年份”添加不可为空的列。

那可能吗?

GMB*_*GMB 5

如果您想添加一个新列并使用另一列中的值对其进行初始化,您可以执行以下操作:

-- 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;
Run Code Online (Sandbox Code Playgroud)