Environment: SQL Server 2016; abstracted example of "real" data.
From a first query to a table containing XML data I have a SQL result set that has the following columns:
- ID (int)
- Names (XML)
- Times (XML)
- Values (XML)
Columns 2-4 contain multiple values in XML format, e.g.
Names:
- Row 1:
<name>TestR1</name><name>TestR2</name>... - Row 2:
<name>TestS1</name><name>TestS2</name>...
Times:
- Row 1:
<time>0.1</time><time>0.2</time>... - Row 2:
<time>-0.1</time><time>-0.2</time>...
Values:
- Row 1:
<value>1.1</value><value>1.2</value>... - Row 2:
<value>-1.1</value><value>-1.2</value>...
The XML of all XML columns contain the exact same number of elements.
What I want now is to create a select that has the following output:
| ID | Name | Time | Value |
+----+--------+------+-------+
| 1 | TestR1 | 0.1 | 1.1 |
| 1 | TestR1 | 0.2 | 1.2 |
| .. | ...... | .... | ..... |
| 2 | TestS1 | -0.1 | -1.1 |
| 2 | TestS2 | -0.2 | -1.2 |
| .. | ...... | .... | ..... |
For a single column CROSS APPLY works fine:
SELECT ID, N.value('.', 'nvarchar(50)') AS ExtractedName
FROM <source>
CROSS APPLY <source>.nodes('/name') AS T(N)
Applying multiple CROSS APPLY statements makes no sense here to me.
I would guess it would work if I would create selects for each column that then produce individual result sets and perform a select over all of the result sets but that's very likely not the best solution as I am duplicating selects for each additional column.
Any suggestions on how to design a query like that would be highly appreciated!