I need your help. Sadly I don’t know SQL as well as I do C# (or most other languages) and I’ve hit my limits with this query. This post may be a bit verbose, so I apologize for that in advance, but I want to make sure I include all the necessary info.
My goal is to create a query that selects data from SQL, groups it by a substring value of one of the columns, and outputs in XML. I’m pretty close, but I’ve hit a wall.
Here’s an example of what it should look like:
<EXAMPLE_DATA>
<headEnd nam="AAAA">
<hardware fromDevice="ExampleDeviceAAAA" />
<hardware fromDevice="ExampleDeviceAAAA" />
<hardware fromDevice="ExampleDeviceAAAA" />
</headEnd>
<headEnd nam="BBBB">
<hardware fromDevice="ExampleDeviceBBBB" />
<hardware fromDevice="ExampleDeviceBBBB" />
<hardware fromDevice="ExampleDeviceBBBB" />
</EXAMPLE_DATA>
As you can see, the last four characters of the fromDevice are what define my headEnd groupings… here’s what I’m able to return right now:
<EXAMPLE_DATA>
<headEnd nam="[headendId]">
<hardware fromDevice="ExampleDeviceAAAA" headendId="AAAA" />
<hardware fromDevice="ExampleDeviceAAAA" headendId="AAAA" />
<hardware fromDevice="ExampleDeviceAAAA" headendId="AAAA" />
<hardware fromDevice="ExampleDeviceBBBB" headendId="BBBB" />
<hardware fromDevice="ExampleDeviceBBBB" headendId="BBBB" />
<hardware fromDevice="ExampleDeviceBBBB" headendId="BBBB" />
</EXAMPLE_DATA>
And finally, here’s the code I have that returns the XML above:
SELECT
'[headendID]' as "@nam"
, (
SELECT hardware.Name as "@fromDevice", RIGHT(hardware.Name, 4) as "@headendId"
FROM tblHardware AS hardware
GROUP BY RIGHT(hardware.Name, 4), hardware.Name
for xml path ('hardware') , type
)
for xml path ('headEnd'), root ('EXAMPLE_DATA')
I’ve removed a lot of non-essential columns to try and make this post a bit easier to read.
So, looking at what I need the XML to look like, is it even possible? I guess anything’s possible… but in this case I’m completely stumped.
Thanks for reading!
EDIT: To make sure my question is clear, what I need is for the SQL code to output XML data grouped by the substring query of hardware.Name. I’m trying to make the output look like the first XML block above.
Here you go: