Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a column to not allow nulls

So I want to change a column in my SQL Server database to not allow nulls, but I keep getting an error. this is the sql statement I am using:

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

and this is the error I am getting :

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.

I'm pretty sure my sql is right, and there are no nulls currently in the column I am trying to change so I am really not sure as to what is causing the problem. Any ideas? I'm stumped.

like image 243
user2255811 Avatar asked Aug 05 '13 22:08

user2255811


People also ask

How do I change a column from NULL to not NULL?

All you need to do is to replace [Table] with the name of your table, [Col] with the name of your column and TYPE with the datatype of the column. Execute the command and you are allowed to use NULL values for the specified column. That is all it takes to switch between NULL and NOT NULL .

How do you add NOT NULL constraints in existing columns?

To add not null constraint to an existing column in MySQL, we will use the ALTER command. This is a type of validation to restrict the user from entering null values.

How do I change a column constraint from not NULL to NULL in Oracle?

NOT NULL constraint specifies that a column cannot contain NULL values. To add a NOT NULL constraint to an existing table by using the ALTER TABLE statement. ALTER TABLE table_name MODIFY ( column_name NOT NULL);


1 Answers

Clearly, the table has NULL values in it. Which you can check with:

select *
from mydatabase
where WeekInt is NULL;

Then, you can do one of two things. Either change the values:

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

Or delete the offending rows:

delete from mydatabase
    where WeekInt is null;

Then, when all the values are okay, you can do the alter table statement.

like image 142
Gordon Linoff Avatar answered Sep 30 '22 06:09

Gordon Linoff