16

所以我想将我的 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 是正确的,并且我正在尝试更改的列中当前没有空值,所以我真的不确定是什么导致了问题。有任何想法吗?我难住了。

4

3 回答 3

17

显然,该表中包含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语句。

于 2013-08-06T00:11:03.790 回答
1

如果您尝试将列更改为不为空,并且收到此错误消息,但该列似乎没有空值,请确保您正在检查is null而不是= null(这会产生不同的结果)。

Select * from ... where column is null

代替

Select * from ... where column = null

我添加这个是因为它让我绊倒并需要一段时间才能解决。

于 2019-02-04T12:57:45.673 回答
0

这将起作用。您应该发送一个默认值,然后在此示例中它将所有先前的记录更改为 -1。

alter table [dbo].[mydatabase] alter column WeekInt int not null DEFAULT '-1';

于 2021-05-27T16:26:19.587 回答