atrenk
atrenk

Reputation: 13

How to add a new column that has the same values as an existing column

I need to add a new column to a table, and the new column should have the same values as an existing column. Is there an easy way to do this? The table doesn't have that many values so I can probably do it manually if necessary, but there must be a better way.

Upvotes: 1

Views: 284

Answers (2)

JonH
JonH

Reputation: 33153

First add the field to your table, depending on if you are using SQL Server you could use management studio to add or issue an ALTER Table command.

ALTER Table MyTable ADD NewColumn varchar(25)

Change the type varchar(25) to match the type of your old column MyOldCol

Then a simple update routine should perform the update:

UPDATE MyTable SET MyNewCol = MyOldCol

Update the values MyTable, MyNewCol, and MyOldCol with yours respectively.

Upvotes: 2

Mike Mozhaev
Mike Mozhaev

Reputation: 2415

I would do

ALTER TABLE MyTable
ADD NewColumn int

UPDATE MyTable SET NewColumn = OldColumn

The only problem is with NON NULL columns. You'll have to provide default value, update and then delete default-value constraint.

Upvotes: 1

Related Questions