Add Column in SQL Server

I need to add a column to a SQL Server table. Can I do this without losing data, do I already have it?

+87
sql-server-2008
Apr 14 2018-11-11T00:
source share
5 answers

Sure! Just use 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 of these is a change in metadata only. The second will update all rows.

In SQL Server 2012+ Enterprise, the second option only changes metadata .

+139
Apr 14 2018-11-11T00:
source share

Use this query:

 ALTER TABLE tablename ADD columname DATATYPE(size); 

And here is an example:

 ALTER TABLE Customer ADD LastName VARCHAR(50); 
+11
Apr 14 '11 at 16:10
source share

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

+2
Apr 14 2018-11-11T00:
source share

Add a new column to the table

 ALTER TABLE [table] ADD Column1 Datatype 

eg

 ALTER TABLE [test] ADD ID Int 

If the user wants him to increase automatically,

 ALTER TABLE [test] ADD ID Int IDENTITY(1,1) NOT NULL 
+1
Apr 10 '17 at 11:12 on
source share

Add a new column to the table with the default value.

 ALTER TABLE NAME_OF_TABLE ADD COLUMN_NAME datatype DEFAULT DEFAULT_VALUE 
-2
Oct 23 '18 at 9:21
source share



All Articles