0

I have a query in a stored procedure retrieving some data in XML format to be returned in a variable @xml_data, like this:

SELECT @xml_data = (
    SELECT * FROM (
        SELECT   1 AS Tag
                ,0 AS Parent
                .....
        FROM    MyTable
        WHERE   id = @id

        UNION ALL

        SELECT   2 AS Tag
                ,1 AS Parent
                ....
        FROM    MyTable2
        WHERE   id = @id

        UNION ALL

        SELECT   3 AS Tag
                ,2 AS Parent
                ....
        FROM    MyTable3
        WHERE   id = @id
    ) results
FOR XML EXPLICIT, TYPE)

This is working like the proverbial dream :)

However, I'd like to concatenate a header to this XML (e.g. <xml version="1.0" encoding="ISO-8859-1"/>) and can't figure out how to do it. I've tried converting to NVARCHAR, selecting the two variables in one statement but can't seem to get it right.

Can anyone help??

Thanks :)

3 Answers 3

1

Try doing like this:

DECLARE @x xml 
DECLARE @strXML varchar(MAX)
SET @x=N'<Employee><Name>Luftwaffe</Name></Employee>'
set @strXML = '<xml version="1.0" encoding="ISO-8859-1"/>' + CONVERT(varchar(MAX),@x)
SELECT @strXML  

Hope it helps !

Sign up to request clarification or add additional context in comments.

Comments

1

You can just declare the string at the beginning and concatenate them together:

declare @xml_data nvarchar(MAX)

set @xml_data = '<xml version="1.0" encoding="ISO-8859-1"/>'

SELECT @xml_data = @xml_data +  (
    SELECT * FROM (
        SELECT   1 AS Tag
                ,0 AS Parent
                .....
        FROM    MyTable
        WHERE   id = @id

        UNION ALL

        SELECT   2 AS Tag
                ,1 AS Parent
                ....
        FROM    MyTable2
        WHERE   id = @id

        UNION ALL

        SELECT   3 AS Tag
                ,2 AS Parent
                ....
        FROM    MyTable3
        WHERE   id = @id
    ) results
FOR XML EXPLICIT, TYPE)

Comments

0

This is the easiest way, in my opinion:

declare @xml1 xml
declare @xml2 xml
declare @xml3 xml
select @xml1='<name>testname</name>'
select @xml2='<value>testvalue</value>'
select @xml3 = 
(
    select @xml1 AS xml1, @xml2 AS xml2
    for xml path('')
)
select @xml3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.