-6

I have a table in SQL server 2008. I need a column that until now wasn't necessary, not to allow NULL anymore, without droping the table. I tried to do something like this:

ALTER TABLE [Sessions] ALTER COLUMN region_id NOT NULL;

EDIT: It was a small syntax error. solved.

Tomer Amir
  • 1,515
  • 4
  • 27
  • 54
  • _"I tried to do something like this"_ ... and what happened? – Tim Schmelter Mar 14 '14 at 11:49
  • You wouldn't have got the answer you got if you included the syntax error message you got in the question. –  Mar 14 '14 at 11:54
  • 1
    No, that most definitely is *not* the message you get for running the query you have in the question. That is the message you get when attempting to change the nullability using the table designer of SSMS. –  Mar 14 '14 at 11:57

4 Answers4

2

You have to specify the data type as well when you alter a column:

ALTER TABLE [Sessions] ALTER COLUMN region_id int /* ? */ NOT NULL;
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
1

You have to first set all values that are NULL to a non NULL value:

UPDATE [Sessions] 
SET region_id=-1
WHERE region_id IS NULL

Instead of -1 you should choose something that would represent the formerly NULL values so you may distinguish them.

To get away with saving prevention you may go on:

Tools>Options>Designers> and unclick Prevent Saving Changes that require table re-creation

Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
1

you are missing datatype.

ALTER TABLE [Sessions] ALTER COLUMN region_id int NOT NULL;

KumarHarsh
  • 5,046
  • 1
  • 18
  • 22
1

First off to save table chances like this you need to either script the changes, or when saving from the UI, you need to set SSMS to drop and recreate table for you. To do this;

Go to Tools Options Designers UNTICK prevent saving changes that require table re-creations.

If you script the changes, you will need to first alter the table, and add a new column allowing nulls. Then update the column and remove nulls and then after you will be able to set the column to NOT NULL.

If you follow these steps you will solve your issue.

Mez
  • 4,666
  • 4
  • 29
  • 57