2

I'm trying to figure out how to extract the AccountNumber on one of my columns with below sample value:

><AccountNumber>12345678</AccountNumber><Links>http://test@test123.com

the string length before and after the account number varies.

I have tried below code but the i cant figure out how to just extract the AccountNumber. Even the account number has different lengths.

Select  substring(XmlData,
                   charindex('><AccountNuber',XMLData),
                 50 )
   from Item with(nolock)
Ellyrose
  • 23
  • 4
  • You may need to have a look to regexp parsing for SQL Server. But only if the is the only purpose of modifying this specific string. Don't user regexp to extensively parse XML or HTML. Use appropriate tool. Maybe SQL Server has XML parsing utility too? this could solve your issue too. – J. Chomel Jun 09 '16 at 07:45
  • Possible duplicate of [SQL Server XML Parsing](http://stackoverflow.com/questions/35445071/sql-server-xml-parsing) – J. Chomel Jun 09 '16 at 07:45
  • checking the link :) – Ellyrose Jun 09 '16 at 08:05

1 Answers1

1

The following solution should work if you only have a single <AccountNumber> tag for each record of the XmlData column.

SELECT SUBSTRING(XmlData,
                 CHARINDEX('<AccountNumber>', XmlData) + 15,
                 CHARINDEX('</AccountNumber>', XmlData) -
                     (CHARINDEX('<AccountNumber>', XmlData) + 15));

If you want to extract multiple values, or if a given record could have multiple tags, then this approach won't work and you should consider using regular expressions, or better yet, an XML parser.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360