I need to generate the following XML string in SQL and assign it to a variable.
<List>
<V Value="TESt">
<Target a="10" b="11"/>
</V>
<T Value="TESt1">
<Target a="100" b="101"/>
</V>
</List>
So, I wrote the following SQL code:
;WITH XML_CTE AS
(
SELECT
1 AS TAG,
NULL AS Parent,
UT.title AS [v!1!Value],
null AS [Target!2!a],
null AS [Target!2!b]
FROM
(
select
10 AS A,
11 AS B,
'TESt' as title
union
select
100 AS a,
101 AS b,
'TESt1' as title
)UT
UNION ALL
SELECT
2,
1,
UT.title AS Value,
ut.a,
ut.b
FROM
(
select
10 AS a,
11 AS b,
'TESt' as title
union
select
100 AS a,
101 AS b,
'TESt1' as title
)ut
)
SELECT * FROM XML_CTE
ORDER BY
[V!1!Value],
[Target!2!a]
FOR XML EXPLICIT, ROOT('List')
But how do I assign it to a xml(or nvarchar) variable? Because of the "UNION ALL", I had to wrap it in CTE, but having it in a CTE, I am unable to assign it to a variable.