1

With SQL Server, is it possible to replace one or more consecutive characters?

For example:

select replace(replace(replace('my string   to  split','  ',' '),'   ',' '),'    ',' ')

without using a loop?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
elle0087
  • 840
  • 9
  • 23

2 Answers2

2

No Need for a LOOP

Here is a little technique Gordon Linoff demonstrated some time ago.

  1. Expand
  2. Elimnate
  3. Restore

You can substitute any ODD combination of characters/strings pairs like §§ and ||

Example

Select replace(replace(replace('my string   to  split',' ','><'),'<>',''),'><',' ')

or More Unique strings

Select replace(replace(replace('my string   to  split',' ','§§||'),'||§§',''),'§§||',' ')

Results

my string to split
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
0

use charindex https://www.w3schools.com/sql/func_sqlserver_charindex.asp in a looping structure and then use a variable to keep track of the index position.

Golden Lion
  • 3,840
  • 2
  • 26
  • 35