简体   繁体   中英

Extract all the XML entry key values as rows using SQL

I'm trying to extract the key values (1,2,3) from a single row in a table, but I'm only able to extract a single row at a time using what I know:

cast([attributes] as XML).value('(//Map/entry[@key="catalogItem"]/value/Map/entry/@key)[1]','VARCHAR(20)')

Depending on what number I put in the [x] I get that entry. I tried removing the [x] and got the error: XQuery [value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'

            <Map>
               <entry key="catalogItem">
                 <value>
                   <Map>
                     <entry key="1" value="x"/>
                     <entry key="2" value="y"/>
                     <entry key="3" value="z"/>

I want the results to be a single column

1

2

3

Please try the following solution.

A combination of XQuery methods .nodes() and .value() gives what you need.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, XMLColumn XML);
INSERT INTO @tbl (XMLColumn) VALUES
(N'<Map>
    <entry key="catalogItem">
        <value>
            <Map>
                <entry key="1" value="x"/>
                <entry key="2" value="y"/>
                <entry key="3" value="z"/>
            </Map>
        </value>
    </entry>
</Map>');
-- DDL and sample data population, end

SELECT t.* 
    , c.value('@key', 'INT') AS [key]
FROM @tbl AS t
    CROSS APPLY XMLColumn.nodes('/Map/entry/value/Map/entry') AS t1(c);

Output

id key
1 1
1 2
1 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM