954,566 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to add not null column in SQL Server 2005

I have to add a not null column in a table.
I am using

IF NOT EXISTS(SELECT * FROM information_schema.columns WHERE column_name = 'xyz' 
AND table_name = 'abc') 	
BEGIN
	ALTER TABLE abc	WITH NOCHECK ADD xyz MONEY NOT NULL
END


It gives me error
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'xyz' cannot be added to non-empty table 'abc' because it does not satisfy these conditions.

can anybody have any idea, what's wrong with my SP?


?

bhavna_816
Junior Poster
116 posts since Sep 2006
Reputation Points: 10
Solved Threads: 0
 

You can't, simply when you add a column all rows before this adding have this column = null, so you can remove all rows and add a non-nullable column.

Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276
 

if you want to add a not null column to a table with rows, you need to set a default value to the new column.

adding a new column without a default value would put a null in the column for each row, which would be breaking the not null rule.

plazmo
Posting Whiz in Training
207 posts since Aug 2005
Reputation Points: 23
Solved Threads: 16
 

U cant add a not null column using ALTER command.Because it allows
to add only null columns.If u want to add datas into that null column you need to use UPDATE command for adding data into that table
Like,

UPDATE TABLE table_name SET null_column-name='value' WHERE column_name='value

EX
UPDATE TABLE employee SET add1='SARA' WHERE sno=1

Saranya_kamaraj
Newbie Poster
1 post since May 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You