title: SQL loop to find all occurrences of a string expression in a DB field
body: <p>I have a <code>varchar(max)</code> field in an SQL Server DB table and I would like to find all occurrences of a string within this field and 50 characters either side to give it context when reading.</p>
  
  <p>I have done this using the code below, but now i would like to adapt it to do it for all occurrences of a string, and for it to appear in one field.</p>
  
  <pre><code>declare @extract varchar(max)
  set @extract = 
  'As Harry squelched along the deserted corridor he came across somebody who looked just as preoccupied as he was. Nearly Headless Nick, the ghost of Gryffindor Tower, was staring morosely out of a window, muttering under his breath, ". . . don''t fulfill their requirements . . . half an inch, if that . . ." 
  "Hello, Nick," said Harry. 
  
  "Hello, hello," said Nearly Headless Nick, starting and looking round. He wore a dashing, plumed hat on his long curly hair, and a tunic with a ruff, which concealed the fact that his neck was almost completely severed. He was pale as smoke, and Harry could see right through him to the dark sky and torrential rain outside. 
  
  "You look troubled, young Potter," said Nick, folding a transparent letter as he spoke and tucking it inside his doublet. 
  
  "So do you," said Harry.'
  
  declare @searchterm varchar(max)
  set @searchterm = '%Harry%'
  
  declare @searchtermlength int = len(@searchterm)
  declare @stringFrom int = (select PATINDEX(@searchterm,@extract) - 50 )
  declare @stringto int = (select PATINDEX(@searchterm,@extract) + @searchtermlength + 50 )
  declare @noChars int = @stringto - @stringfrom
  
  select SUBSTRING(@extract,@stringFrom,@noChars)
  </code></pre>
  
  <p>This returns <code>'As Harry squelched along the deserted corridor he came acros'</code> but I would like it to return:</p>
  
  <pre><code>As Harry squelched along the deserted corridor he came acros...
  ...f an inch, if that . . ." "Hello, Nick," said Harry. "Hello, hello," said Nearly Headless Nick, sta
  ...ost completely severed. He was pale as smoke, and Harry could see right through him to the dark sky and tor...
  ...king it inside his doublet. "So do you," said Harry.
  </code></pre>
  
  <p>I'm guessing that this can be done using a loop but I've never really used one before so any help would be greatly appreciated.</p>
  
  <p>Thanks in advance</p>