简体   繁体   中英

Retrieve (Shredding) Multiple Values in SQL Server into same cell (row/ column intersection) in table from XML data column

I have a table (T) with an xml data column (XMLcol) and an ID column.

===========================

Following is the XML data:

"( <RootNode>    
<Node1>    
<Line_id_Node>1 </Line_id_Node>    
<A>    
<B>    
<D>Val1 </D>    
</B>    
<B>    
<D>Val2 </D>    
</B>    
<B>    
<D>Val3 </D>    
</B>    
</A>    
</Node1>


<Node1>    
<Line_id_Node> 2 </Line_id_Node>    
<A>    
<B>    
<D>Val4 </D>    
</B>    
<B>    
<D>Val2 </D>    
</B>    
</A>    
</Node1>


<Node1>    
<Line_id_Node> 3 </Line_id_Node>    
<A>    
<B>    
<D>Val5 </D>    
</B>    
</A>    
</Node1>    
</RootNode>)"

Expected O/P:

-------------------------------------------------
Line_id_Node                Column_D
-------------------------------------------------
1                           val1, val2, val3
2                           val4, val2
3                           val5

I want to get all the three values above in a SINGLE Cell. Tried cross apply, creating variable etc. but didn't nail a proper syntax.

If you can at least give an example of how to concatenate values in similar nodes with XML, that would also help. I want something that will act in the same way as we use ...STUFF with FOR XML PATH ( for comma separated output).

Should we use an @XMLhandle,

sp_xml_preparedocument

@XMLDocument, 

sp_xml_removedocument

?? Any help will be highly appreciated!

Thank you.

DECLARE @T TABLE (id int, XMLcol xml)
INSERT @T VALUES
(1,'<C><D>Val1 </D></C><C><D>Val2 </D></C><C><D>Val3 </D></C>'),
(2,'<C><D>Val4 </D></C><C><D>Val5 </D></C><C><D>Val6 </D></C>')

SELECT id,(
  SELECT STUFF((SELECT ','+v.value('D[1]','varchar(max)')
  FROM @T
  CROSS APPLY XMLCol.nodes('C') x1(v)
  WHERE id = t.id
  FOR XML PATH('')
  ),1,1,'')
)
FROM @T t

--------------------
id  (No column name)
1   Val1 ,Val2 ,Val3 
2   Val4 ,Val5 ,Val6 

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