title: SQL Extract Values from a String
body: <p>How do I extract values from a string?  I'm trying to separate into 3 new columns.  A separate column for city, state and zipcode.</p>
  
  <p>I've tried</p>
  
  <pre><code>select address2,
  left(address2, charindex('',address2)-1)
  from table
  </code></pre>
  
  <p>and ---when I try the below code I get "Invalid length parameter passed to the left or substring function"</p>
  
  <pre><code>,LTRIM(substring(a.Address2, CHARINDEX(' ', a.Address2)+1, CHARINDEX(' ', substring(a.address2, charindex(' ',
  a.address2)+1, len(a.address2)))-1))
  </code></pre>
  
  <p>I can break out the city (except for West Warwick) using the following code, but not sure how to make it work for state and zip.  This also removes the error.</p>
  
  <pre><code>SUBSTRING(Address2,1,CHARINDEX(' ', a.address2+ ' ')-1) as city
  </code></pre>
  
  <p>Any ideas what to try?</p>
  
  <p><a href="https://i.stack.imgur.com/0CuR8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0CuR8.jpg" alt="enter image description here"></a></p>