Question

I have the following problem.

My table, say tab1, has name column as follows "LastName, FirstName". I want to make it so that the column becomes "FirstName LastName".

Any ideas on how this is to be done? Note that there is no comma present, but i guess that can be easily removed once I figure out how to actually flip the first and the last names.

Any help would be appreciated.

Thanks.

Was it helpful?

Solution

replace @NAME with your real value:

SELECT TRIM(SUBSTR(@NAME, LOCATE(",", @NAME) + 1)) AS prename, TRIM(SUBSTR(@NAME, 1, LOCATE(",", @NAME) - 1)) AS surename

This will extract the prename and surename part, now you can insert/modify the data as you want to.

OTHER TIPS

  • It would be better to split the name column into two fields, FirstName and LastName, so that you can format them in any way you want, and still sort on last name.
  • Use substring and substring_index to find comma's and split on them. See the manual.

Not an answer to your question, but I would not do this under any circumstances. You will lose any chance to reliably tell apart last name and first name. Consider the following names:

Bridget St John
Boutros Boutros Ghali
Karl-Theodor Maria Nikolaus Freiherr von und zu Guttenberg

I recommend keeping separate "last name" and "first name" columns. You can concatenate them as you please when you do your output.

UPDATE table SET name2=CONCAT (TRIM(SUBSTR(name, LOCATE(",", name) + 1)), ' ', TRIM(SUBSTR(name, 1, LOCATE(",", name) - 1)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top