The Answers to the Question Returning multiple rows from querying XML column in SQL Server 2008 were helpful. But I have an XML data set with a slightly different structure and need help getting valid query output.
Here's the code that demonstrates my problem.
DECLARE @XML_In XML = '
<ROOT>
<PROCESS_RESULT>
<CATEGORY>ABC</CATEGORY>
<STATUS>ERROR</STATUS>
<PROCESS_RESULT_MSG>
<MESSAGE_TEXT>ABC Process Category Error</MESSAGE_TEXT>
</PROCESS_RESULT_MSG>
</PROCESS_RESULT>
<PROCESS_RESULT>
<CATEGORY>XYZ</CATEGORY>
<STATUS>ERROR</STATUS>
<PROCESS_RESULT_MSG>
<MESSAGE_TEXT>XYZ Process Category Error</MESSAGE_TEXT>
</PROCESS_RESULT_MSG>
</PROCESS_RESULT>
</ROOT>'
DECLARE @XMLTab TABLE ( MyXMLTable XML)
INSERT INTO @XMLTab ( MyXMLTable ) VALUES( @XML_In )
SELECT MyXMLTable FROM @XMLTab
SELECT b.query('data(CATEGORY)') AS CATEGORY
,b.query('data(STATUS)') AS STATUS
,a.query('data(MESSAGE_TEXT)') AS MESSAGE_TEXT
FROM @XMLTab
CROSS APPLY
MyXMLTable.nodes('ROOT/PROCESS_RESULT/PROCESS_RESULT_MSG') x(a)
CROSS APPLY
MyXMLTable.nodes('ROOT/PROCESS_RESULT') y(b)
The two queries return the following outputs. The first is fine. The second is obviously incorrect.
How might I change the SELECT statement to accurately output the data, i.e., relating the MESSAGE_TEXT values to the proper CATEGORY and STATUS key?