My source data in a SQL Server table has XML structured data. For each of the source rows I need to query the following sample XML structure in a way that I get a calculated value of all A sub elements. For example the SUM of bb
and product of cc * dd
over all A elements.
The number of A elements in the structure is unknown.
<root>
<A>
<bb>bb1</bb>
<cc>cc1</cc>
<dd>dd1</dd>
</A>
<A>
<bb>bb2</bb>
<cc>cc2</cc>
<dd>dd2</dd>
</A>
<A>
<bb>bb3</bb>
<cc>cc3</cc>
<dd>dd3</dd>
</A>
</root>
I experimented with something like this, but it looks like not being the right way:
SELECT Convert(xml,myXmlCol).value('(/root/A[1]/bb)[1]', 'int') as MyResult FROM SourceTable
Best Answer
The below query uses this sample data:
It declares 2 different variables and insert in in a dummy table. This is only a table with 2 rows:
Query:
It read each row from the table and extract XML data.
Output:
If can then be used with a
GROUP BY
:Output