Search code examples
sqlt-sqlcharindex

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


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.


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).