Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join on data from XML in T-SQL

I have the following XML message:

DECLARE @XML AS XML
SET @XML = 
'<Message>
<Changes>
    <Deleted>
        <ROW id="1" name="Nicole" surname="Bartlett" city="denver" balance="779.4663" dateOfBirth="1991-12-11T14:05:42.830" maritalStatus="S" />
        <ROW id="1" name="Nicole" surname="Bartlett" city="boston" balance="779.4663" dateOfBirth="1991-12-11T14:05:42.830" maritalStatus="S" />
    </Deleted>
    <Inserted>
        <ROW id="1" name="Nicole" surname="Bartlett" city="denver" balance="779.4663" dateOfBirth="1991-12-11T14:05:42.830" maritalStatus="S" />
        <ROW id="1" name="Nicole" surname="Bartlett" city="boston" balance="779.4663" dateOfBirth="1991-12-11T14:05:42.830" maritalStatus="S" />
    </Inserted>
</Changes>
</Message>'

And I need to select data from this message and join another table on id field. The following code doesn't work:

SELECT T.c.value('./@id', 'int') as id, t.c.value('./@name', 'varchar(max)') as name 
FROM @XML.nodes('/Message/Changes/Deleted/ROW') T(c)
inner join other_table tbl
    on tbl.id = id

How can I do this?

like image 373
Marian Zagoruiko Avatar asked May 08 '12 12:05

Marian Zagoruiko


People also ask

How do I query XML data in SQL?

SQL Server provides the XQuery feature to querying XML data type or querying with the XML column with the XPATH. Using XQuery, users can Insert, Update and Delete with the XML nodes and node values in an XML column.

How do I combine two XML files in SQL Server?

How to merge the xml content of @a and @b into @c ? declare @a xml = (select 1 aaa for xml path('AAAs')); declare @b xml = (select 1 bb1, 2 bb2 for xml path('BBBs')); declare @c xml = ...


1 Answers

SELECT T.c.value('./@id', 'int') as id, t.c.value('./@name', 'varchar(max)') as name 
FROM @XML.nodes('/Message/Changes/Deleted/ROW') T(c)
inner join other_table tbl
    on tbl.id = T.c.value('./@id', 'int')
like image 72
Mikael Eriksson Avatar answered Oct 30 '22 06:10

Mikael Eriksson