I have the following query:
SELECT
[ID] AS [NewID]
, (
CASE WHEN LEN([MiddleName]) > 0 THEN
[LastName] + ', ' + [FirstName] + ' ' + LEFT([MiddleName],1) + '.'
ELSE
[LastName] + ', ' + [FirstName]
END
) AS [Name]
, [Title] AS [ProfTitle]
, CONVERT(CHAR(10),[DepartureDate],111) AS [BorDepart]
, [LocationOfficeNumber] AS [OfficePhone]
, [Location]
, [LocationSection] AS [Sec]
, [PracticeGroup] AS [PracticeTL]
, [Email]
FROM [dbo].[Borrowers]
With that, I'd like to find out how I can write a FOR XML query that translate to this output:
<sydney>
<import>
<template id="Borrower" name="Borrowers">
<record searchfield="NewID" searchvalue="NewID">
<field id="NewID">
<![CDATA[NEWID]]>
</field>
<field id="Name">
<![CDATA[NAME]]>
</field>
<field id="ProfTitle">
<![CDATA[Professional Title]]>
</field>
<field id="BorDepart">
<![CDATA[YYYY/MM/DD]]>
</field>
<field id="OfficePhone">
<![CDATA[office phone]]>
</field>
<link id="Location" linkfield="Code">
<![CDATA[011]]>
</link>
<link id="Sec" linkfield="Term">
<![CDATA[SECTION]]>
</link>
<link id="PracticeTL" linkfield="Term">
<![CDATA[SUBSECTION]]>
</link>
<field id="Email">
<![CDATA[email]]>
</field>
</record>
</template>
</import>
</sydney>
I've tried all kinds of combinations with FOR XML PATH and FOR XML EXPLICIT and cannot find any answer to it. The closest I came is with this:
SELECT (
SELECT
'Borrower' AS '@id'
, 'Borrowers' AS '@name'
, (
SELECT
'NewID' AS '@searchfield'
, 'NewID' AS '@searchvalue'
, [ID] AS 'NewID' --AS [Field!1!CDATA]
, (
CASE WHEN LEN([MiddleName]) > 0 THEN
[LastName] + ', ' + [FirstName] + ' ' + LEFT([MiddleName],1) + '.'
ELSE
[LastName] + ', ' + [FirstName]
END
) AS [Name]
, [Title] AS [ProfTitle]
, CONVERT(CHAR(10),[DepartureDate],111) AS [BorDepart]
, [LocationOfficeNumber] AS [OfficePhone]
, [Location]
, [LocationSection] AS [Sec]
, [PracticeGroup] AS [PracticeTL]
, [Email]
FROM [dbo].[Borrowers]
FOR XML PATH('record'), TYPE
)
FOR XML PATH('template'), TYPE
) AS 'import'
FOR XML PATH('sydney'), TYPE
Please any help is welcome since I've been stuck with this for a week and cannot find anything.
P.S.: Here's the schema for the Borrowers table:
Cheers,
Alvaro Costa
Best Answer
Here is a working
FOR XML EXPLICIT
example. They are a bit harder to code, but I tend to build them up, section by section so they're not so bad:HTH