How to extract data from a xml field

  • Hi folks.

    I have a field of type xml.

    It contains data of the following format <a><b>1234</b</a>

    I want to extract the number as a int in a query.

    select XmlField.query('/a/b') from myTable

    returns

    <b>1000</b>

    <b>1001</b>

    <b>1002</b>

    How do I specify the query to return the values as

    1000

    1001

    1002

    Thanks

    Christian

  • Try this,

    CREATE TABLE tblXML (ID INT PRIMARY KEY, xmlVal XML not null)

    insert into tblXML values(2,'<a><b>1234</b></a><a><b>222</b></a><a><b>333</b></a>')

    select * from tblXML

    SELECT x.query('b').value('.','varchar(100)') as Product

    FROM tblXML CROSS APPLY xmlVal.nodes('/a') AS Tref(x)

    Result:

    Product

    1234

    222

    333

  • This post shouldn’t be in the SQL Server 2000/7, because those versions don’t support Xquery. Having said that, the method query returns an untyped xml (just as you discovered). The method value returns the value of the element or attribute, but it can return only one value. In order to get the values for more then one node, you’ll need to work with the node method combined with the value method. Below is a small example:

    declare @xml xml

    set @xml =

    '<root>

    <a>

    <b>1234</b>

    </a>

    <a>

    <b>5678</b>

    </a>

    </root>'

    select tbl.col.value('.','int')

    from @xml.nodes('/root/a/b') tbl (col)

    Adi

    --------------------------------------------------------------
    To know how to ask questions and increase the chances of getting asnwers:
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Thanks that was exactly what I was looking for.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply