【发布时间】:2018-02-28 16:38:42
【问题描述】:
我正在尝试将 XML 字段放入 SQL 变量(然后最终放入表列),但出现错误。
如果我跑步
Declare @tvTable Table (
id int IDENTITY(1,1)
,someThing varchar(100)
,otherThing varchar(100)
,thisThing varchar(100)
);
Insert @tvTable
Values ('stuff', 'blah', 'foo')
,('thing', 'data', 'bob');
Select [Tag] = 1
,[PARENT] = NULL
,[things!1!thingId] = NULL
,[thing!2!thingId!element] = NULL
,[thing!2!thingOne!element] = NULL
,[thing!2!thingTwo!cdata] = NULL
,[thing!2!thingThree!cdata] = NULL
UNION ALL
Select 2
,1
,1
,thingId = id
,thingOne = someThing
,thingTwo = otherThing
,thingThree = thisThing
From @tvTable
FOR XML EXPLICIT;
然后我会收到适当的回报
<things>
<thing>
<thingId>1</thingId>
<thingOne>stuff</thingOne>
<thingTwo><![CDATA[blah]]></thingTwo>
<thingThree><![CDATA[foo]]></thingThree>
</thing>
<thing>
<thingId>2</thingId>
<thingOne>thing</thingOne>
<thingTwo><![CDATA[data]]></thingTwo>
<thingThree><![CDATA[bob]]></thingThree>
</thing>
</things>
但是,一旦我尝试将其转储到变量中,就会出现错误:
The FOR XML clause is invalid in views, inline functions, derived tables, and
subqueries when they contain a set operator. To work around, wrap the SELECT
containing a set operator using derived table syntax and apply FOR XML on top
of it.
我需要使用XML EXPLICIT,因为我需要将某些字段包装在正确的 CDATA 标记中(最初的尝试只是将它们作为字符串放入,而供应商拒绝了该文件)。
如何修改此查询,以便将返回值存储在变量中?
【问题讨论】:
标签: xml tsql sql-server-2014