I need to make the XML nodes disappear if the value is NULL or empty string.
Using the {$contact/Name} works just fine, but in this case I cannot do it.
Here is the code:
DECLARE @t TABLE
(
id int,
Name varchar(20),
OfficeNumber varchar(20),
MobilePhone varchar(20),
Faxnumber varchar(20)
)
INSERT @t SELECT 1,'Liang', NULL, '654238','5478'
INSERT @t SELECT 2,'Jia','123512','45689','12565478'
INSERT @t SELECT 3,'Hui','9542654','123789','42165'
SELECT
(
SELECT
id AS [@id],
Name AS [Name],
OfficeNumber AS [phonenumber/@OfficePhone],
MobilePhone AS [phonenumber/@MobilePhone],
Faxnumber AS [phonenumber/@Faxnumber]
FROM @t AS A
FOR XML PATH('contact'),TYPE
).query('
<root>
{
for $contact in /contact
return
<contact id="{$contact/@id}">
{$contact/Name}
<PhoneNumber type="Office">{data($contact/phonenumber/@OfficePhone)}</PhoneNumber>
<PhoneNumber type="Mobile">{data($contact/phonenumber/@MobilePhone)}</PhoneNumber>
<PhoneNumber type="Fax">{data($contact/phonenumber/@Faxnumber)}</PhoneNumber>
</contact>
}
</root>
')
Current output is:
<root>
<contact id="1">
<Name>Liang</Name>
<PhoneNumber type="Office" />
<PhoneNumber type="Mobile">654238</PhoneNumber>
<PhoneNumber type="Fax">5478</PhoneNumber>
</contact>
...
</root>
The desired output would be:
<root>
<contact id="1">
<Name>Liang</Name>
<PhoneNumber type="Mobile">654238</PhoneNumber>
<PhoneNumber type="Fax">5478</PhoneNumber>
</contact>
...
</root>
I'm using SQL Server 2008 and 2012.