• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 302
  • Last Modified:

I want to add a new column with a default value.

I want to add a new column with a default value.

When I add the column will the default value be set the existing rows or will it only apply to new rows?

        ALTER TABLE [dbo].[shop]
        ADD [hasCSV] BIT CONSTRAINT DF_hasCSV DEFAULT 0  
0
Mr_Shaw
Asked:
Mr_Shaw
  • 3
  • 3
2 Solutions
 
sventhanCommented:
< When I add the column will the default value be set the existing rows or will it only apply to new rows?

Only new rows. You've to update the existing rows manually.
0
 
mayank_joshiCommented:
if you define NOT NULL on the column the existing rows will be updated atomatically.
0
 
sventhanCommented:
Sorry. If its a new column you should be fine with this statement...

 ALTER TABLE [dbo].[shop]
        ADD [hasCSV] BIT CONSTRAINT DF_hasCSV DEFAULT 0
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
mayank_joshiCommented:
on the other hand if you define NULL on the column existing rows will not be updated and the default value will be set only on new rows.


ALTER TABLE {TABLENAME} 
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} 
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}

Open in new window


0
 
mayank_joshiCommented:
what i m trying to say is:-

 ALTER TABLE [dbo].[shop]
 ADD [hasCSV] BIT NOT NULL CONSTRAINT DF_hasCSV DEFAULT 0   

Open in new window

this will update the existing rows.
0
 
sventhanCommented:
okay. if you use this

ALTER TABLE [dbo].[shop]
        ADD [hasCSV] BIT CONSTRAINT DF_hasCSV DEFAULT 0


you should do this ...

update [dbo].[shop]  set hascsv = 0 where hascsv is null

Sorry for the confusion....

0
 
Mr_ShawAuthor Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now