Reversing a CharIndex in a Stuff function to find and replace first occurrece of a character

StackOverflow https://stackoverflow.com/questions/22973923

  •  30-06-2023
  •  | 
  •  

Question

I'm trying to find and replace the first space from right to left and replace it with a comma.

Before results: "Peter & Lois Griffin"

This is my current string:

SET [Last Name/Organization Name]=STUFF([Last Name/Organization Name],CHARINDEX(' ',([Last Name/Organization Name])),LEN(' '),',')

After results: Peter, & Lois Griffin

What do I need to change to make my results be: Peter & Lois, Griffin ?

Thanks for the help.

Was it helpful?

Solution

I don't have a SQL Server at hand to test it, but you could take advantage of REVERSE():

SET [Last Name/Organization Name]=STUFF(
    [Last Name/Organization Name],
    LEN([Last Name/Organization Name])-1-CHARINDEX(' ',REVERSE([Last Name/Organization Name])),
    LEN(' '),
    ',')

(plus you would have to treat empty string).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top