Alternate table with new not null Column in existing table in SQL

Sql Server

Sql Server Problem Overview


How to add not null Column in existing table in SQL Server 2005?

Sql Server Solutions


Solution 1 - Sql Server

You will either have to specify a DEFAULT, or add the column with NULLs allowed, update all the values, and then change the column to NOT NULL.

ALTER TABLE <YourTable> 
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>

Solution 2 - Sql Server

Choose either:

a) Create not null with some valid default value
b) Create null, fill it, alter to not null

Solution 3 - Sql Server

There are two ways to add the NOT NULL Columns to the table :

  1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

  2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''

Solution 4 - Sql Server

The easiest way to do this is :

ALTER TABLE db.TABLENAME ADD COLUMN [datatype] NOT NULL DEFAULT 'value'

Ex : Adding a column x (bit datatype) to a table ABC with default value 0

ALTER TABLE db.ABC ADD COLUMN x bit NOT NULL DEFAULT 0

PS : I am not a big fan of using the table designer for this. Its so much easier being conventional / old fashioned sometimes. :). Hope this helps answer

Solution 5 - Sql Server

IF NOT EXISTS (SELECT 1
FROM syscolumns sc
JOIN sysobjects so
ON sc.id = so.id
WHERE so.Name = 'Table1'
AND sc.Name = 'Col1')
BEGIN
ALTER TABLE Table1
ADD Col1 INT NOT NULL DEFAULT 0;
END
GO

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyogeswaran KView Question on Stackoverflow
Solution 1 - Sql ServerAdriaan StanderView Answer on Stackoverflow
Solution 2 - Sql ServerzerkmsView Answer on Stackoverflow
Solution 3 - Sql Serveruser3602795View Answer on Stackoverflow
Solution 4 - Sql ServerArvind SrikanthView Answer on Stackoverflow
Solution 5 - Sql ServerAnil SomanView Answer on Stackoverflow