我需要在 SQL 中生成以下 XML 字符串并将其分配给一个变量。
<List>
<V Value="TESt">
<Target a="10" b="11"/>
</V>
<T Value="TESt1">
<Target a="100" b="101"/>
</V>
</List>
因此,我编写了以下 SQL 代码:
;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')
但是如何将它分配给 xml(或 nvarchar)变量?由于“UNION ALL”,我不得不将它包装在 CTE 中,但是将它放在 CTE 中,我无法将它分配给变量。