将FOR XML EXPLICIT UNION的结果分配给变量

时间:2013-02-13 16:57:07

标签: sql-server-2008 for-xml-explicit

此查询正常

SELECT 1 AS TAG, NULL AS parent, 1 [dog!1]
UNION (SELECT 1,NULL, 3) 
FOR XML EXPLICIT, ROOT('dogs')

我想将它分配给变量。没有联合,这可以正常工作:

DECLARE @x xml
SET @x = ((
  (SELECT 1 AS TAG, NULL AS parent, 1 [dog!1]
   FOR XML EXPLICIT, ROOT('dogs'))
  )) 

一旦我介绍了工会,它就不起作用了:

DECLARE @x xml
SET @x = ((
  (SELECT 1 AS TAG, NULL AS parent, 1 [dog!1]
   UNION (SELECT 1,NULL, 3) 
   FOR XML EXPLICIT, ROOT('dogs'))
   )) 

尝试过各种各样的事情。我缺少什么

1 个答案:

答案 0 :(得分:3)

您只需要再添加一个子查询级别:

DECLARE @X XML = 
(
  SELECT * FROM
  (
    SELECT 1 AS TAG, NULL AS parent, 1 [dog!1]
    UNION 
    SELECT 1,NULL, 3
  )X
  FOR XML EXPLICIT, ROOT('dogs')
);

SELECT @X;