XML declaration with "FOR XML PATH" in SQL Server 2005

Davin Studer picture Davin Studer · Jan 22, 2010 · Viewed 12.6k times · Source

Below is a simplified version of a query that I have already created. The query works fine, but I cannot figure out how to get the XML declaration at the top of the generated XML. I've tried multiple things and searched far and wide on the Google, but alas I cannot seem to find out how to do this ... or even if it is possible.

select 
    'Dimension' "@type",
    (
        select
            (
                select
                    'X102' "TransactionType",
                    convert(varchar, getdate(), 104) "Transfer/TransferDate",
                    convert(varchar, getdate(), 108) "Transfer/TransferTime"
                for xml path (''), type
            ) "TransactionInformation"
        for xml path (''), type
    )
for xml path ('DimensionImport'), type

Gives me...

<DimensionImport type="Dimension">
    <TransactionInformation>
        <TransactionType>X102</TransactionType>
        <Transfer>
            <TransferDate>21.01.2010</TransferDate>
            <TransferTime>15:46:36</TransferTime>
        </Transfer>
    </TransactionInformation>
</DimensionImport>

I'm wanting...

<?xml version="1.0" encoding="ISO-8859-1" ?>
<DimensionImport type="Dimension">
    <TransactionInformation>
        <TransactionType>X102</TransactionType>
        <Transfer>
            <TransferDate>21.01.2010</TransferDate>
            <TransferTime>15:46:36</TransferTime>
        </Transfer>
    </TransactionInformation>
</DimensionImport>

Thank you in advance for any help you might be able to lend.

Answer

Rob Farley picture Rob Farley · Jan 22, 2010

It's messy, but you could just concatenate it on the front...

SELECT '<? xml...>' + 
(select 
    'Dimension' "@type",
    (
        select
            (
                select
                    'X102' "TransactionType",
                    convert(varchar, getdate(), 104) "Transfer/TransferDate",
                    convert(varchar, getdate(), 108) "Transfer/TransferTime"
                for xml path (''), type
            ) "TransactionInformation"
        for xml path (''), type
    )
for xml path ('DimensionImport'), type)