简体   繁体   中英

T-SQL - Convert/Transpose multiple XML node values to a column

I have an simple XML field in a table which stores one or more values within it's nodes:

<MultiSelect>
  <ItemKey>38</ItemKey>
  <ItemKey>36</ItemKey>
</MultiSelect>

How do I query this field in such a way that these values are extracted to a column in the result?

Source data:

RowKey    Format
-----------------
1         <MultiSelect><ItemKey>40</ItemKey></MultiSelect>
2         <MultiSelect><ItemKey>40</ItemKey><ItemKey>36</ItemKey></MultiSelect>

Aiming for result:

RowKey   ItemKey
----------------
1        40
2        40
2        36

I've got close to where I want to be with the query below, but this is only returning the NAME of the XML nodes rather than the values within them:

SELECT 
    [RowKey],
    x.y.value('local-name(.)', 'varchar(max)') AS ItemKey

FROM
[tbl_MyDataTable] AS t
    cross apply t.[Format].nodes('MultiSelect/ItemKey') x(y)

Result:

RowKey   ItemKey
----------------
1       ItemKey
2       ItemKey
2       ItemKey

Any suggestions greatfully recieved!

You're close - try this (since those are all INT numerical values, I'd recommend using INT in your XQuery):

SELECT 
    [RowKey],
    x.y.value('(.)[1]', 'INT') AS ItemKey
FROM
    dbo.[tbl_MyDataTable] AS t
CROSS APPLY
    t.[Format].nodes('/MultiSelect/ItemKey') x(y)

Basically, by selecting (.)[1] , you're selecting the value of the node - not it's name (which is ItemKey )

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