How to concatenate data from a SQL Server XML query?
Asked Answered
M

2

5

I have a SQL query that returns me the XML below

<row>
  <urlSegment>electronics</urlSegment>
  <shortenedUrlSegment>0x58</shortenedUrlSegment>
</row>
<row>
  <urlSegment>phones</urlSegment>
  <shortenedUrlSegment>0x5AC0</shortenedUrlSegment>
</row>
<row>
  <urlSegment>curvy-simplicity</urlSegment>
  <shortenedUrlSegment>65546</shortenedUrlSegment>
</row>

etc

The output that I want is is a table with two columns (Url and ShortenedUrl) with the data concatenated in a url fashion as shown below.

Url                                  | ShortenedUrl
electronics/phones/curvy-simplicity  | 0x58/0x5AC0/65546

etc

Can anyone help?

Best of regards

Menticide answered 18/9, 2013 at 5:25 Comment(0)
A
7

you can use xquery like this:

select
    stuff(
        @data.query('
            for $i in row/urlSegment return <a>{concat("/", $i)}</a>
        ').value('.', 'varchar(max)')
    , 1, 1, '') as Url,
    stuff(
        @data.query('
            for $i in row/shortenedUrlSegment return <a>{concat("/", $i)}</a>
        ').value('.', 'varchar(max)')
    , 1, 1, '') as ShortenedUrl

sql fiddle demo

Aegis answered 3/10, 2013 at 20:36 Comment(3)
Even thought I am not using XML anymore, this works lovely. Thanks.Menticide
Was doing this another way that wouldn't handle multiple sub-groups of strings to concatenate and this completely solved the issue. Much cleaner than before also. Thanks!Riehl
Absolutely lovely!Jacindajacinta
P
1

Try this:

DECLARE @input XML

SET @input = '<row>
  <urlSegment>electronics</urlSegment>
  <shortenedUrlSegment>0x58</shortenedUrlSegment>
</row>
<row>
  <urlSegment>phones</urlSegment>
  <shortenedUrlSegment>0x5AC0</shortenedUrlSegment>
</row>
<row>
  <urlSegment>curvy-simplicity</urlSegment>
  <shortenedUrlSegment>65546</shortenedUrlSegment>
</row>'

SELECT
    Url = XRow.value('(urlSegment)[1]', 'varchar(100)'),
    ShortenedUrl =XRow.value('(shortenedUrlSegment)[1]', 'varchar(100)')
FROM
    @input.nodes('/row') AS XTbl(XRow)

The .nodes() gives you a sequence of XML fragments, one for each <row> node in your XML. Then you can "reach into" that <row> element and fish out the contained subelements.

Ponce answered 18/9, 2013 at 5:32 Comment(1)
That gets me 1/2 way there, but I need to concatenate each row in each column so the data in both columns would be (Url)electronics/phones/curvy-simplicity & (UrlShortened) 0x58/0x5AC0/65546Menticide

© 2022 - 2024 — McMap. All rights reserved.