3

I am using SQL Server 2014 and I have a table named Table1. Assuming I want to duplicate a column named SubCategory into a new column called SubCategory2 (with the same values as in column SubCategory), what would be the SQL syntax to do this?

Note: Idea here is to keep column Subcategory but create another column SubCategory2 and modify some specific values in that new column.

Example (assuming Table1 has only 2 columns):

Serial  Subcategory
  1        UK
  2        UK
  3        FR
  4        DE

Expected output:

Serial  Subcategory  Subcategory2
  1        UK           UK
  2        UK           UK
  3        FR           FR
  4        DE           DE
user3115933
  • 4,303
  • 15
  • 54
  • 94

4 Answers4

16

A combination of Add a column with a default value to an existing table in SQL Server and How can I copy data from one column to another in the same table? woold look something like:

ALTER TABLE Table1
ADD SubCategory2 {Type of subcategory 1} {NULL|NOT NULL} 
UPDATE Table1 SET SubCategory2 = SubCategory;
kabanus
  • 24,623
  • 6
  • 41
  • 74
1
select * from Table1


---------Query-----------

select * , SubCategory as SubCategory2 FROM Table1

----------------------

enter image description here

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Ravi Sharma
  • 362
  • 1
  • 5
0

Use case instead when selecting records

     SELECT Serial ,Subcategory,  case 
      when Subcategory='somevalue' 
      then Subcategory else null end
     'Subcategory2'  from table
Himanshu
  • 3,830
  • 2
  • 10
  • 29
-2
 use ['database name']
   go
 insert into table1 ('subcategory2') select subgategory from table1;
Eugene Ogongo
  • 335
  • 3
  • 12