Replace Function With Recursive CTE
Last 2 posts we learned some cool ways to use the STUFF function. This post, we will combine the power of recursive common table expression ( CTE ), STUFF and PATINDEX function to write our own script to replace a string pattern. Some of you may ask why bother when SQL Sever already has the built-in REPLACE function? Well, this is just for fun and it doesn't hurt to practice writing sql. : ) /*********************************************************************** Replace a pattern with another string pattern. This is almost the same as the built-in TSQL REPLACE function. Ex: remove all commas within a string. ************************************************************************/ -- DECLARE @original_str VARCHAR(100) = 'The, quick, brown, fox, jumps, over, the, lazy, dog' , @pattern_str VARCHAR(100) = ',' , @replacement_str VARCHAR(100) = ''; -- recursive CTE: replace @pattern_str with @replacement_str ; WITH phrase(string, row_i...