Question

I have a fairly big SELECT ... FOR XML PATH. As you know, by default xml elements corresponding to fields with a null value don't appear in the result xml tree. It appears to be a real problem for me and I want to always have ALL the elements appear, whether the value is null or not.

Is there a way to achieve that without surrounding each field by ISNULL(...,'') one by one (more than 50 fields in my SELECT !) and without changing the FOR XML PATH into FOR XML ELEMENTS to use the XSINIL switch (which is unfortunately available only with ELEMENTS) ?

I suspect these 2 not-entirely-statisfying solutions would result in different outputs, by the way : <fieldname></fieldname> and <fieldname/> respectively. If possible I'd prefer the first one, but I am anyway eager to read your precious suggestions.

Thanks in advance ! :-)

Was it helpful?

Solution

without changing the FOR XML PATH into FOR XML ELEMENTS to use the XSINIL switch

You can use elements xsinil with for xml path.

declare @T table (ID int identity, Name varchar(50))

insert into @T values ('Name1')
insert into @T values (null)
insert into @T values ('Name2')

select
  ID,
  Name
from @T
for xml path('item'), root('root'), elements xsinil

Result:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <item>
    <ID>1</ID>
    <Name>Name1</Name>
  </item>
  <item>
    <ID>2</ID>
    <Name xsi:nil="true" />
  </item>
  <item>
    <ID>3</ID>
    <Name>Name2</Name>
  </item>
</root>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top