如何在列的默认值中添加NOT NULL约束?

时间:2020-10-28 08:11:47

标签: sql sql-server

我在学生表中有一列“名称”。我需要在此列上添加NOT NULL约束。但是我收到SQL错误,说不能添加空约束,因为表中的现有行在列中具有空值。如何在单个alter语句中添加空约束和默认值。以下是我的查询。

alter table Student alter column name nvarchar NOT NULL;

2 个答案:

答案 0 :(得分:1)

但是我收到SQL错误,说不能添加空约束,因为表中的现有行在列中具有空值。

您是否尝试覆盖现有的NULL值?

当现有值违反该约束时,您不能在列上具有约束。您需要首先使表兼容。

答案 1 :(得分:1)

SQL Server并不容易做到这一点。我认为唯一的方法是将现有值设置为所需的默认值。然后将列更改为默认值和not null

-- Get rid of the existing `NULL` values
update students set name = '' where name is null;

-- Add the NOT NULL constraint
alter table students
    alter column name varchar(255) not null;

-- Add a default value
alter table students
    add constraint df_t_name default '' for name ;

Here是实际的样子。