title: SQL Server validating postcodes
body: <p>I have a table containing postcodes but there is no validation built in to the entry form so there is no consistency in the way they are stored in the database, sample below:</p>
  
  <pre><code>ID      Postcode
  001742  B5
  001745  
  001746  
  001748  DY3
  001750  
  001751  
  001768  B276LL
  001774  B339HY
  001776  B339QY
  001780  WR51DD
  </code></pre>
  
  <p>I want to use these postcode to map the distance from a central point but before I can do that I need to put them into a valid format and filter out any blanks or incomplete postcodes.</p>
  
  <p>I had considered using</p>
  
  <pre><code>left(postcode,3) + ' ' + right(postcode,3)
  </code></pre>
  
  <p>To correct the formatting but this wouldn't work for postcodes like 'M6 8HD'</p>
  
  <p>My aim is to get the list of postcodes in a valid format but I don't know how to account for different lengths of postcode. Is this there a way to do this in SQL Server?</p>