Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column to a table with a default value equal to the value of an existing column

How to add a column to a SQL Server table with a default value that is equal to value of an existing column?

I tried this T-SQL statement:

ALTER TABLE tablename  ADD newcolumn type NOT NULL DEFAULT (oldcolumn)  

but it's giving an error:

The name "oldcolumn" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

like image 318
doesdos Avatar asked Nov 06 '12 11:11

doesdos


People also ask

How do you add a column to a specific position in an existing table?

To add a column at a specific position within a table row, use FIRST or AFTER col_name . The default is to add the column last. You can also use FIRST and AFTER in CHANGE or MODIFY operations to reorder columns within a table.

How do I add a column and data to an existing table?

Step 1: Create a new column with alter command. ALTER TABLE table_name ADD column_name datatype; Step 2: Insert data in a new column.

Can we add column to the existing table with data?

If you know SQL then you probably know that you can add columns to an existing table in SQL Server using the ALTER command. It not only allows you to add a column but to drop columns as well. You can also add or drop constraints using the ALTER command.


2 Answers

Try this:

ALTER TABLE tablename ADD newcolumn type NOT NULL DEFAULT (0) Go Update tablename SET newcolumn = oldcolumn Where newcolumn = 0 Go 
like image 195
Kapil Khandelwal Avatar answered Oct 06 '22 14:10

Kapil Khandelwal


The AFTER INSERT trigger approach involves overhead due to the extra UPDATE statement. I suggest using an INSTEAD OF INSERT trigger, as follows:

CREATE TRIGGER tablename_on_insert ON tablename  INSTEAD OF INSERT  AS INSERT INTO tablename (oldcolumn, newcolumn) SELECT oldcolumn, ISNULL(newcolumn, oldcolumn) FROM inserted 

This does not work though if the oldcolumn is an auto-identity column.

like image 37
Herman Kan Avatar answered Oct 06 '22 15:10

Herman Kan