title: SQL Server xml string parsing in varchar field
body: <p>I have a varchar column in a table that is used to store xml data. Yeah I know there is an xml data type that I should be using, but I think this was set up before the xml data type was available so a varchar is what I have to use for now. :)</p>
  
  <p>The data stored looks similar to the following:</p>
  
  <pre><code>&lt;xml filename="100100_456_484351864768.zip"  
       event_dt="10/5/2009 11:42:52 AM"&gt;
      &lt;info user="TestUser" /&gt;
  &lt;/xml&gt;
  </code></pre>
  
  <p>I need to parse the filename to get the digits between the two underscores which in this case would be "456". The first part of the file name "shouldn't" change in length, but the middle number will. I need a solution that would work if the first part does change in length (you know it will change because "shouldn't change" always seems to mean it will change).</p>
  
  <p>For what I have for now, I'm using XQuery to pull out the filename because I figured this is probably the better than straight string manipulation. I cast the string to xml to do this, but I'm not an XQuery expert so of course I'm running into issues. I found a function for XQuery (substring-before), but was unable to get it to work (I'm not even sure that function will work with SQL Server). There might be an XQuery function to do this easily, but if there is I am unaware of it.</p>
  
  <p>So, I get the filename from the table with a query similar to the following:</p>
  
  <pre><code>select CAST(parms as xml).query('data(/xml/@filename)') as p
  from Table1
  </code></pre>
  
  <p>From this I'd assume that I'd be able to CAST this back to a string then do some instring or charindex function to figure out where the underscores are so that I can encapsulate all of that in a substring function to pick out the part I need. Without going too far into this I am pretty sure that I can eventually get it done this way, but I know that there has to be an easier way. This way would make a huge unreadable field in the SQL Statement which even if I moved it to a function would still be confusing to try to figure out what is going on.</p>
  
  <p>I'm sure there is an easier than this since it seems to be simple string manipulation. Perhaps someone can point me in the right direction. Thanks</p>