How to Duplicate Column in same table in SQL
-
17-03-2021 - |
Pergunta
I'm pretty basic with SQL and need help with the following task:
I already have a table with data in it. What I would like to do is to Duplicate a Column (Including the data) in the same table but with a different column name. Is this possible?
Any help would be greatly appreciated.
Solução
You can just add the new column to the table as nullable, either with SQL Server Management Studio by right clicking on the Table and clicking "Design" or by using an ALTER TABLE
statement like this ALTER TABLE TableName ADD NewColumnName DataType NULL
.
Then you can UPDATE
that new column from the old column like so:
UPDATE TableName
SET NewColumnName = OldColumnName
Outras dicas
Depending on other requirements, you might be able to get away with using a computed column. This assumes you don't need to manipulate the data in the duplicated column.
ALTER TABLE dbo.t
ADD NewColumn AS OldColumn;