将列更改为不允许空值

use*_*811 12 sql-server null alter-column

所以我想更改我的SQL Server数据库中的列不允许空值,但我一直收到错误.这是我正在使用的sql语句:

alter table [dbo].[mydatabase] alter column WeekInt int not null
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'WeekInt', table 'CustomerRadar.dbo.tblRWCampaignMessages'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
Run Code Online (Sandbox Code Playgroud)

我很确定我的sql是正确的,并且我正在尝试更改的列中当前没有空值,所以我真的不确定导致问题的原因.有任何想法吗?我很难过.

Gor*_*off 12

显然,该表中包含NULL值.您可以查看:

select *
from mydatabase
where WeekInt is NULL;
Run Code Online (Sandbox Code Playgroud)

然后,你可以做两件事之一.要么改变值:

update mydatabase
    set WeekInt = -1
    where WeekInt is null;
Run Code Online (Sandbox Code Playgroud)

或删除有问题的行:

delete from mydatabase
    where WeekInt is null;
Run Code Online (Sandbox Code Playgroud)

然后,当所有值都可以时,您可以执行该alter table语句.