tags:

views:

126

answers:

5

I have a table that I want to add a bit column, which I wish to default to false for all existing data.

How do I alter my table in such a way that it allows me to specify NOT NULL before I have inserted false for my existing rows?

Should I create it as nullable, do an insert than switch it non-nullable?

A: 

I have also done it as you say "create it as nullable, do an insert than switch it non-nullable". I've not had a problem doing it this way.

I've not yet needed to find a better way, however I'm intrigued if there is another way....

MrEdmundo
+6  A: 

You could add the column and provide the default value to be used for all existing rows.

ALTER TABLE foo 
ADD bar bit 
DEFAULT 0 NOT NULL;
Robert Christie
I typically like to NAME my constraint - even default constraints - in case I need to drop them later on. The default "DF__TimeZones__IsUsa__3D5E1FD2" names are a bit hard to remember.....
marc_s
A: 

I usually create the field as nullable with a default as false in your case update all the fields that were in the database prior then switch it to null

jmein
+1  A: 
ALTER TABLE dbo.MyTable ADD MyColumn bit NOT NULL DEFAULT 0

For what it is worth, you can fire up Enterprise Manager, make the changes in the UI, and then have it generate a Change Script - and you can see how it would accomplish these kinds of tasks.

Bryan Batchelder
+2  A: 
ALTER TABLE foo ADD bar bit DEFAULT 0 NOT NULL WITH VALUES;

The "with values" clause propigates the default value into existing rows.

Cylon Cat
@marc_s, I just ran it without the "WITH VALUES" for my bit column and it worked. Are you sure?
KingNestor
@KingNestor, try it with a default value of 1, or something that's not all binary zeros.
Cylon Cat
WITH VALUES is used in the case of a NULLABLE column and you want the default value to be used instead of NULL.
Bryan Batchelder
@KingNestor: you're absolutely right - if the column is defined as NOT NULL, it will be filled with the default value even without the "WITH VALUES" clause. Thanks for pointing that out! But the WITH VALUES is needed if the column is defined as NULLable
marc_s