I am trying to write a query that returns XML using t-sql. When I run a query that does not have any sibling elements the closing tags are left as is and NOT converted to self closing tags.
create table #seg
(
HouseHoldExternalId int,
Id int
)
insert into #seg
select 2534640, 265 union
select 2534644, 265 union
select 2534650, 265 union
select 2534661, 265 union
select 2534669, 265 union
select 2534684, 265 union
select 2534689, 265 union
select 2534692, 265 union
select 2534694, 265 union
select 2534698, 265
select
1 as 'Id',
(
select
HouseHoldExternalId as 'HouseHoldExternalId',
(
select null as 'Blank',
(
select Id as 'Id', 1 as 'Status',
(
select '' for xml path (''), type
)
from #seg as aa
where aa.HouseHoldExternalId = a.HouseHoldExternalId
for xml raw ('Segment'), type
)
for xml raw ('HouseHoldSegments'), type
)
from #seg as a
for xml raw ('HouseHold'), type
)
for xml raw ('retailer'), type
A snippet from the resulting xml shows the full closing tag.
<Segment Id="265" Status="1"></Segment>
When I try to adjust my query to return a result with sibling elements, the closing tags are changed to be self closing. How can I get the full closing to stay?
select
1 as 'Id',
(
select
HouseHoldExternalId as 'HouseHoldExternalId',
(
select null as 'Blank',
(
select Id as 'Id', 1 as 'Status',
(
select '' for xml path (''), type
)
from #seg as aa
where aa.HouseHoldExternalId = a.HouseHoldExternalId
for xml raw ('Segment'), type
)
for xml raw ('HouseHoldSegments'), type
)
from #seg as a
for xml raw ('HouseHold'), type
),
(
select
HouseHoldExternalId as 'HouseHoldExternalId',
(
select null as 'Blank',
(
select Id as 'Id', 1 as 'Status',
(
select '' for xml path (''), type
)
from #seg as aa
where aa.HouseHoldExternalId = a.HouseHoldExternalId
for xml raw ('Segment'), type
)
for xml raw ('HouseHoldSegments'), type
)
from #seg as a
for xml raw ('HouseHold'), type
)
for xml raw ('retailer'), type
A snippet from the resulting xml shows the self closing tag which I do not want.
<Segment Id="265" Status="1" />