I’m trying to get a result of FOR XML query as a text.
I’ve found some similar question here:
Using SQL Server "FOR XML": Convert Result Datatype to Text/varchar/string whatever?
but in my case I use WITH XMLNAMESPACES statement and this solution doesnt work for me.
How can I get a result of this following query as a text?
WITH XMLNAMESPACES ('urn:blablablabla' as bi)
SELECT 'urn:blablabla.xsd' AS "@xsi:schemaLocation",
(SELECT 'aaaa' AS 'bi:idValue',
'bbbb' AS 'bi:idContext'
FOR XML PATH('bi:Part1'),TYPE),
(SELECT 'cccc' AS 'bi:idValue',
'dddd' AS 'bi:idContext'
FOR XML PATH('bi:Part2'),TYPE)
FOR XML PATH('bi:Items'), ELEMENTS XSINIL
Thanks
The result should look like this:
<bi:Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bi="urn:blablablabla" xsi:schemaLocation="urn:blablabla.xsd">
<bi:Part1 xmlns:bi="urn:blablablabla">
<bi:idValue>aaaa</bi:idValue>
<bi:idContext>bbbb</bi:idContext>
</bi:Part1>
<bi:Part2 xmlns:bi="urn:blablablabla">
<bi:idValue>cccc</bi:idValue>
<bi:idContext>dddd</bi:idContext>
</bi:Part2>
</bi:Items
My goal is to get this result as a text and not as XML datatype.
For example to do something like that:
DECLARE @ResultText NVARCHAR(MAX)
SET @ResultText = ... Returned text from this query ...
In addition maybe you know how can I avoid repeating of namespace in each node?
Thank you
You need to use
selectinstead ofset.Update:
According to these two answers there is a way to do it with
for xml explicit.FOR XML PATH and xsi:nil attributes
How do I remove redundant namespace in nested query when using FOR XML PATH
If you want the behavior to change for the future you can vote on this connect item.
suppress namespace attributes in nested SELECT FOR XML statements