I have a list of users in a table, with separate fields for first, middle, and last name. For various reasons, I need to change the database structure such that there is only one "name" field. What is the best/easiest way to migrate my data from the 3 old fields into my one new field?
The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value.
To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.
If you have SQL Server 2017 or later, using CONCAT_WS() is the best way to concatenate multiple columns to a string value. Here you have to specify the separator in the form of char, nchar, varchar or nchar as the first argument. Then you can pass on the columns to concatenate in the subsequent arguments.
First add a column that is longer than all 3 combined.
alter table tbl add fullname varchar(100);
Next, update it with the concatenation of the old columns.
update tbl set fullname = concat(lastname, ', ', firstname, ' ', middlename)
(This ends up in the form 'Kirk, John M')
Then, remove the old columns
alter table tbl drop column firstname;
alter table tbl drop column middlename;
alter table tbl drop column lastname;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With