Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

FOR XML PATH e atributos xsi:nil


Eu não acho que seja possível evitar esse comportamento com subconsultas usando for xml path . Há um problema semelhante relatado aqui. https ://connect.microsoft.com/SQLServer/feedback/details/265956/suppress-namespace-attributes-in-nested-select-for-xml-statements

Você pode obter a saída desejada se usar for xml explicit em vez de.
declare @T table(Level1 int, Level2 int)
insert into @T values(null, 2)

select 1    as Tag,
       null as Parent,
       null as [root!1],
       null as [nested1!2!level1!ELEMENTXSINIL],
       null as [nested1!2!level2!ELEMENTXSINIL],
       null as [nested2!3!level1!ELEMENTXSINIL],
       null as [nested2!3!level2!ELEMENTXSINIL]
union all
select 2    as Tag,
       1    as Parent,
       null,
       Level1,
       Level2,
       null,
       null
from @T       
union all
select 3    as Tag,
       1    as Parent,
       null,
       null,
       null,
       Level1,
       Level2
from @T       
for xml explicit       

Resultado:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <nested1>
    <level1 xsi:nil="true" />
    <level2>2</level2>
  </nested1>
  <nested2>
    <level1 xsi:nil="true" />
    <level2>2</level2>
  </nested2>
</root>