Quantcast
Channel: Eric Niemiec's Blog » SQL Server
Viewing all articles
Browse latest Browse all 10

SQL Server XML – FOR XML PATH not returning empty XML for NULLS, OMITTING NULLS

$
0
0

I have a simple query that joins an Appointments table to a Calendars table (INNER JOIN). Then I have a situation where if the Appointment item is associated with a Lead, it is joined to the Leads table to grab a few other pieces of information, if the Appointment item is not, it is considered a note (LEFT OUER JOIN). I assumed (silly me) that the XML would render the same way that a table would render and include the NULL columns/values, and would just leave them blank. Not the case – the same query, two different XML nodes in the result set contained two different sets of fields.

Here is the original query, that returns two different set of fields in the same result set if one row has a corresponding lead and one doesn’t.

Below is the resulting XML – from the same query. The columns marked in yellow only exist when the LEFT OUTER JOIN matches, but when it doesn’t, it omits the XML tag completely in the second row.

If you look at the SQL Server documentation, there are several ways of getting this to work – switching to FOR XML EXPLICIT is one of them among many. I found an easy and acceptable solution by formatting the select list a bit and was able to solve my problem. The only down site to this is that the string fields were returned empty as expected, but integer fields came back with a zero, not empty – a problem I decided I could live with. Some of the other solutions I found online required a lot more work and knowledge of XML ‘ELEMENTS XSINIL’. Again, doesn’t look very hard to use this method, but when you have vendors pulling this data and expecting the XML to look one way, then you through in things like this: <FieldName xsi:nil=”true” />, it tends to throw them off a bit.

Here is the updated query, modifying only the select portion of the statement and using a CASE statement on those fields involved in the LEFT OUTER JOIN and that could come back as null.

And here is the results from the above query with the failed LEFT OUTER JOIN fields highlighted in yellow.

Another day, another thing learned.



Viewing all articles
Browse latest Browse all 10

Trending Articles