Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating xml values when selecting by XQuery in T-SQL

This is my sample XML:

<root>
    <element>
        <subelement>
            <value code="code1">value1</value>
            <value code="code2">value2</value>
        </subelement>
    </element>
</root>

And this is my test query:

DECLARE @tempTable TABLE (
    ValueCode nvarchar(MAX),
    Value nvarchar(MAX)
)

DECLARE @xml XML
select @xml = cast(c1 as xml) from OPENROWSET (BULK 'C:\test.xml', SINGLE_BLOB) as T1(c1)

INSERT INTO @tempTable
SELECT 
    Tbl.Col.value('subelement[1]/@code', 'NVARCHAR(MAX)'),
    Tbl.Col.value('subelement[1]', 'NVARCHAR(MAX)')
FROM @xml.nodes('//element') Tbl(Col)

SELECT * FROM @tempTable

The query, when executed, gives out a row with the ValueCode column containing NULL and the Value column containing 'value1value2'. What I would like to get would be the attributes and values concatenated with a separator. For example, I need ValueCode to contain 'code1; code2' and Value to contain 'value 1; value2'. How can I achieve that?

like image 635
sdds Avatar asked Sep 03 '13 07:09

sdds


People also ask

How do I query XML data in XQuery?

Querying in an XQuery context If your query invokes an XQuery expression directly, you must prefix it with the case-insensitive keyword XQUERY. To retrieve all of the XML documents previously inserted into the INFO column, you can use XQuery with either db2-fn:xmlcolumn or db2-fn:sqlquery.


Video Answer


1 Answers

you can use xuery if you want concatenated strings:

SELECT 
    Tbl.Col.query('for $i in value return concat($i/text()[1], ";")').value('.', 'nvarchar(max)'),
    Tbl.Col.query('for $i in value return concat($i/@code, ";")').value('.', 'nvarchar(max)')
FROM @xml.nodes('root/element/subelement') Tbl(Col);

if you want your values into rows:

SELECT 
    Tbl.Col.value('.', 'nvarchar(max)'),
    Tbl.Col.value('@code', 'nvarchar(max)')
FROM @xml.nodes('root/element/subelement/value') Tbl(Col);

sql fiddle demo

like image 116
Roman Pekar Avatar answered Oct 16 '22 11:10

Roman Pekar