SQL Server XML输出与CDATA成xml变量

时间:2017-11-15 20:28:48

标签: sql-server xml cdata

question之后,我需要将select结果放入xml变量中。如何避免错误消息“FOR XML和FOR JSON子句在视图,内联函数,派生表和子查询中包含set运算符时无效。要解决此问题,请使用派生表包装包含set运算符的SELECT或公用表表达式或视图,并在其上应用FOR XML或FOR JSON。“,拜托?

这里是测试代码:

declare @agent table
(    
    AgentID int,
    Fname varchar(5),
    SSN varchar(11)
)

insert into @agent
select 1, 'Vimal', '123-23-4521' union all
select 2, 'Jacob', '321-52-4562' union all
select 3, 'Tom', '252-52-4563'

SELECT
    1 AS Tag,
    NULL AS Parent,
    NULL AS 'Agents!1!',
    NULL AS 'Agent!2!AgentID',
    NULL AS 'Agent!2!Fname!Element',
    NULL AS 'Agent!2!SSN!cdata'
UNION ALL
SELECT
    2 AS Tag,
    1 AS Parent,
    NULL, 
    AgentID,
    Fname,
    SSN
FROM @agent
FOR XML EXPLICIT

这是我想做的一个例子:

Declare @xml xml
...
set @xml= (SELECT
    1 AS Tag,
    NULL AS Parent,
    NULL AS 'Agents!1!',
    NULL AS 'Agent!2!AgentID',
    NULL AS 'Agent!2!Fname!Element',
    NULL AS 'Agent!2!SSN!cdata'
UNION ALL
SELECT
    2 AS Tag,
    1 AS Parent,
    NULL, 
    AgentID,
    Fname,
    SSN
FROM @agent
FOR XML EXPLICIT)

1 个答案:

答案 0 :(得分:1)

这很棘手......

您可以将UNION ALL部分移至此处CTE。问题不在于FOR XML,而在于UNION(请注意,可能需要添加ORDER BY子句):

DECLARE @xml XML;

WITH UnionAllCte AS
(
    SELECT
        1 AS Tag,
        NULL AS Parent,
        NULL AS 'Agents!1!',
        NULL AS 'Agent!2!AgentID',
        NULL AS 'Agent!2!Fname!Element',
        NULL AS 'Agent!2!SSN!cdata'
    UNION ALL
    SELECT
        2 AS Tag,
        1 AS Parent,
        NULL, 
        AgentID,
        Fname,
        SSN
    FROM @agent
)
SELECT @xml=
(
    SELECT * FROM UnionAllCte
    FOR XML EXPLICIT
)

SELECT @xml;

您应该知道,CDATA以及FOR XML EXPLICIT已过时。而是使用FOR XML PATH()并阅读相应的methods the XML data type provides

might read this并阅读以下链接!