将列更改为不允许空值

ua4mk5z4  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(301)

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

zbdgwd5y

zbdgwd5y1#

显然,这张table 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 声明。

balp4ylt

balp4ylt2#

如果试图将列更改为not null,并且收到此错误消息,但该列似乎没有null,请确保正在检查 is null 而不是 = null (给出了不同的结果)。

Select * from ... where column is null

而不是

Select * from ... where column = null

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

相关问题