更改列不允许为空

问题描述 投票:11回答:2

所以,我想在我的SQL Server数据库更改列不允许为空,但我不断收到一个错误。这是我使用的SQL语句:

alter table [dbo].[mydatabase] alter column WeekInt int not null

这是我得到的错误:

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.

我敢肯定,我的SQL是正确的,目前有在列没有空,我试图改变,所以我真的不知道,什么原因造成的问题。有任何想法吗?我难倒。

sql-server null alter-column
2个回答
12
投票

很显然,该表NULL在它的值。您可以与检查:

select *
from mydatabase
where WeekInt is NULL;

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

update mydatabase
    set WeekInt = -1
    where WeekInt is null;

或删除违规行:

delete from mydatabase
    where WeekInt is null;

然后,当所有的值都还好,你可以做alter table声明。


0
投票

如果你想一列更改为NOT NULL,并且您收到此错误信息,但它出现在列没有空值,确保您检查is null而不是= null(其给出不同的结果)。

Select * from ... where column is null

代替

Select * from ... where column = null

我加入这个,因为它绊倒我,花了一段时间来解决。

© www.soinside.com 2019 - 2024. All rights reserved.