Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate data from a SQL Server XML query?

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

like image 869
dezzy Avatar asked Sep 18 '13 05:09

dezzy


People also ask

How can I get SQL query results in XML?

You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.

What is concat in XML?

The XMLConcat() function concatenates two XML objects (either two elements or two attributes) to produce a single XML object.

How do I process XML data in SQL Server?

Process XML data using OPENXML function Now as I said before, XML data stored in a column of data type XML can be processed either by using XML functions available in SQL Server or by using the sp_xml_preparedocument stored procedure along with the OPENXML function.


2 Answers

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

like image 141
Roman Pekar Avatar answered Sep 21 '22 09:09

Roman Pekar


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.

like image 36
marc_s Avatar answered Sep 25 '22 09:09

marc_s