XML EXPLICIT变量

时间:2017-09-19 19:12:15

标签: xml tsql sql-server-2014

我试图将一个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标记中(初始尝试只是将它们作为字符串输入,并且供应商拒绝了该文件)。

如何修改此查询,以便将返回值存储在变量中?

1 个答案:

答案 0 :(得分:2)

处理变量集上的XML而不是查询本身。

def named_decorater(func):
    def func_named(*, x):
        return func(x)
    return func_named

@named_decorater
def foo(x):
    print(x)

foo(2)   #error
foo(x=2) #works