在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)
答案 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并阅读以下链接!