Skip to content
Advertisement

How to limit STUFF function within CTE for removing character before recurring word

A follow up question for Replace a recurring word and the character before it

Credit to @Larnu for the following code, how would this code be modified to not produce a null value if there is no longer a character before a recurring word, “[BACKSPACE]”. I believe the null value is occurring because the CHARINDEX() functions are producing a negative value when there is no longer a character before the recurring [BACKSPACE] word. The solution would need to be compatible with SQL Server 2008.

The ultimate goal is for anywhere that there is a [BACKSPACE], IF there is a character before [BACKSPACE], remove it; otherwise, don’t try to remove the character before.

The desired output is 'SecondWord'

Advertisement

Answer

You need a CASE check to see if you are at the beginning of the string, in which case you don’t want the position before, as that is 0.

Some other improvements I would make to this code: LEN could be calculated once, and we could store the [BACKSPACE] value in a variable also

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement