SET XML EXPLICIT QUERY TO VARIABLE

时间:2013-01-17 19:31:47

标签: sql-server sql-server-2008 tsql

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

2 个答案:

答案 0 :(得分:3)

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

SELECT @MyVariable = 
    (SELECT * FROM XML_CTE 
    ORDER BY 
        [V!1!Value], 
    [Target!2!a]
    FOR XML EXPLICIT, ROOT('List')
    )

答案 1 :(得分: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>

正如你所要求的那样。