简体   繁体   中英

TSql xml query is concatenating values

When I query an xml column in a temp variable, the results are being concatenated if an xml element has multiple values. Below is an excerpt from the xml column-

 <metadata>
   <dataType>Date</dataType>
    <tags>
      <tag>SPA</tag>
      <tag>Timed Release</tag>
    </tags>
 </metadata>

Notice the two tag elements. I need one row for each tag element. Here is my query-

 SELECT id,
    dataType = [Type].value('(/metadata/tags)[1]', 'varchar(max)')
 FROM
@tmpProperty

that produces the below

 id   | dataType
 -----+-------------------
 6357 | SPATimed Release

if I change the query to

 SELECT id,
dataType = [Type].value('(/metadata/tags/tag)[1]', 'varchar(max)')
FROM
@tmpProperty

I get

 id   | dataType
 -----+-----------
 6357 | SPA

Both results are wrong. One concatenates into a single row instead of 2 rows, and the other just returns one value. I am using sql server 2012. How can I fix this?

You need to use nodes() first to get multiple rows, then you can use value() to extract the data:

DECLARE @tmpProperty TABLE (ID INT IDENTITY, [Type] XML);
INSERT @tmpProperty([Type])
VALUES ('<metadata>
   <dataType>Date</dataType>
    <tags>
      <tag>SPA</tag>
      <tag>Timed Release</tag>
    </tags>
 </metadata>');

 SELECT id,
        dataType = Tags.value('(text())[1]', 'varchar(max)')
 FROM   @tmpProperty AS t
        CROSS APPLY t.[Type].nodes('/metadata/tags/tag') AS n (Tags);

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