I’m new to the “FOR XML” feature in SQL Server. I am using SQL Server 2012.
I have two tables, Word and Word_Expansion.
Sample data:
table [Word]:
WordOID Word
------- ----
1 PIPE
2 WIRE
table [Word_Expansion]:
WEOID fk_WordOID Word_Expansion
----- ---------- --------------
1 2 COAX
2 2 SPEAKER CABLE
3 1 CONDUIT
Now, I would like to produce XML something like:
<expansion>
<sub>WIRE</sub>
<sub>SPEAKER CABLE</sub>
</expansion>
<expansion>
<sub>PIPE</sub>
<sub>CONDUIT</sub>
</expansion>
I have come close with various efforts at crafting XML FOR statements, but I just can’t seem to grasp what it is that I need to do to get these two tables mashed into the right XML output. I’ll be digging further into XML FOR syntax, but if you have a moment and know this well…
Does anyone have any pointers as to what I should try?
This should do the trick for you:
SQL:
XML Output:
Although i’m not sure why you want Word.Word to be classified as “Sub”?
Shouldn’t this instead be the parent of Word_Expansion (which should be sub?)
EDIT: I found this link quite useful when looking into FOR XML and nested queries Nested FOR XML