Skip to content
Advertisement

How to extract attribute value from XML in SQL Server 2019 (v15)?

I would need to extract elements from this XML into a tabular form, but I can’t seem to get my head around how this would work on SQL Server via something like XQuery.

I have all the data in a temporary table called “#1” and the XML itself lies in a field called “Message” in that temporary table. How can I extract the values “Test1” and “2,2 %” into separate fields called “W08003” and “W1A081”, respectively? The attribute names and the schema will remain the same over time? I would also need to do this on a row by row basis for each XML in the current temporary table.

Current SQL code:

Advertisement

Answer

With no expected results, perhaps this is enough to get you started.

As you define a default namespace only once you get to status, you can’t use a DEFAULT namespace in XMLNAMESPACES, so I name it ns and reference that instead. This gives you the value of all the terms and their id attribute:

I note that the XML has been changed since the initial version I used to write this answer. This answer has not been (read “won’t be”) adjusted for that.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement