title: Escape a string in SQL Server so that it is safe to use in LIKE expression
body: <p>How do I escape a string in SQL Server's stored procedure so that it is safe to use in <code>LIKE</code> expression.</p>
  
  <p>Suppose I have an <code>NVARCHAR</code> variable like so:</p>
  
  <pre><code>declare @myString NVARCHAR(100);
  </code></pre>
  
  <p>And I want to use it in a <code>LIKE</code> expression:</p>
  
  <pre><code>... WHERE ... LIKE '%' + @myString + '%';
  </code></pre>
  
  <p>How do I escape the string (more specifically, characters that are meaningful to <code>LIKE</code> pattern matching, e.g. <code>%</code> or <code>?</code>) in T-SQL, so that it is safe to use in this manner?</p>
  
  <p>For example, given:</p>
  
  <pre><code>@myString = 'aa%bb'
  </code></pre>
  
  <p>I want:</p>
  
  <pre><code>WHERE ... LIKE '%' + @somehowEscapedMyString + '%'
  </code></pre>
  
  <p>to match <code>'aa%bb'</code>, <code>'caa%bbc'</code> but not <code>'aaxbb'</code> or <code>'caaxbb'</code>.</p>