4

我需要在 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 中,我无法将它分配给变量。

4

2 回答 2

3

您可以将SELECT * FROM XML_CTE...语句更改为以下内容

SELECT @MyVariable = 
    (SELECT * FROM XML_CTE 
    ORDER BY 
        [V!1!Value], 
    [Target!2!a]
    FOR XML EXPLICIT, ROOT('List')
    )
于 2013-01-17T20:47:20.343 回答
3

假设您有一组初始数据,例如:

Col1     A     B
------------------
TESt     10    11
TESt1   100   101

那么我建议使用FOR XML PATH,ROOT而不是旧的遗留EXPLICIT模式(这真的很复杂和令人费解)

DECLARE @result NVARCHAR(MAX)

;WITH XML_CTE(Col1, A, B) AS
(
  SELECT 
     'TESt', 10, 11
  UNION
  SELECT    
    'TESt1', 100, 101
)
SELECT @Result =
   (SELECT
       Col1 AS '@Value',
       A AS 'Target/@a',
       B AS 'Target/@b'
    FROM XML_CTE 
    FOR XML PATH('V'), ROOT('List')
   )

给我一个输出:

<List>
  <V Value="TESt">
    <Target a="10" b="11" />
  </V>
  <V Value="TESt1">
    <Target a="100" b="101" />
  </V>
</List>

正如你所要求的。

于 2013-01-17T20:47:23.637 回答