Add column to SQL Server

Sql Server-2008

Sql Server-2008 Problem Overview


I need to add a column to my SQL Server table. Is it possible to do so without losing the data, I already have?

Sql Server-2008 Solutions


Solution 1 - Sql Server-2008

Of course! Just use the ALTER TABLE... syntax.

Example

ALTER TABLE YourTable
  ADD Foo INT NULL /*Adds a new int column existing rows will be 
                     given a NULL value for the new column*/

Or

ALTER TABLE YourTable
  ADD Bar INT NOT NULL DEFAULT(0) /*Adds a new int column existing rows will
                                    be given the value zero*/

In SQL Server 2008 the first one is a metadata only change. The second will update all rows.

In SQL Server 2012+ Enterprise edition the second one is a metadata only change too.

Solution 2 - Sql Server-2008

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);

Solution 3 - Sql Server-2008

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

Solution 4 - Sql Server-2008

Add new column to Table

ALTER TABLE [table]
ADD Column1 Datatype

E.g

ALTER TABLE [test]
ADD ID Int

If User wants to make it auto incremented then

ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL

Solution 5 - Sql Server-2008

Add new column to Table with default value.

ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE

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
QuestionAntarr ByrdView Question on Stackoverflow
Solution 1 - Sql Server-2008Martin SmithView Answer on Stackoverflow
Solution 2 - Sql Server-2008bhavesh NView Answer on Stackoverflow
Solution 3 - Sql Server-2008Alex K.View Answer on Stackoverflow
Solution 4 - Sql Server-2008Chiragkumar ThakarView Answer on Stackoverflow
Solution 5 - Sql Server-2008Rakesh Singh BalharaView Answer on Stackoverflow