Why would you use “Stuff” instead of “Replace?”

Good question.  Both perform a similar function – replace a string with another string (or no string at all), but Replace has a simpler syntax.

The Replace function looks like this:

select replace('abcdef','bc','xx')

result: axxdef

No locations to find, just replace the string.  However, what if we had a string with two occurrences of the string, like:

select replace('abcabcabc','abc','123')

result: 123123123

If we only wanted to replace the first one, Replace wouldn’t work, since it always replaces ALL occurrences of the string. But Stuff would, since it only replaces the string it finds at the starting location we tell it for the number of chars we want it to replace. 

select stuff('abcabcabc',4, 3,'123')

result: abc123abc

Since I tend to prefer explicit control of strings (to reduce the possibility of unintended substitutions), I will usually grab Stuff rather than Replace.  The overhead is probably slightly less for Stuff since the function already knows where to look for the value, but I don’t consider that a deal breaker.

One Comment to “DBTalk – Stuff vs Replace”

  1. Thanks for your writing. I would also love to say that the health insurance brokerage service also works best for the benefit of the particular coordinators of your group insurance policies. The health insurance broker is given a long list of benefits wanted by somebody or a group coordinator. Exactly what a broker will is seek out individuals or coordinators which will best complement those desires. Then he reveals his advice and if all sides agree, this broker formulates a legal contract between the two parties.

Leave a Reply

You can wrap your code with [ruby][/ruby] or [python][/python] blocks for syntax highlighting and you can use these traditional tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>