如何在数据进入一行时格式化XML代码

时间:2016-12-06 13:07:10

标签: sql sql-server xml

我有样本数据

DECLARE @Table1 TABLE (users int, ts int, name varchar(10), [1] int);

INSERT INTO @Table1 (users, ts, name, [1])
VALUES (1, 1, 'Raj', 0),
       (1, 3, 'maj', 2534),
       (1, 10, 'yes', 1458);

脚本

select
    'test' as 'job/branch/FBEN/opcode',
    users AS 'job/branch/FBEN/opcode',
    name as 'job/branch/FBEN/opcode' 
from 
    @Table1
where 
    ts = 1
for xml path('xmlexecute'), elements;

输出:

<xmlexecute>
  <job>
    <branch>
      <FBEN>
        <opcode>test1Raj</opcode>
      </FBEN>
    </branch>
  </job>
</xmlexecute>

我怎么能这样呢?

<xmlexecute>
  <job>
    <branch>
      <FBEN>
        <opcode>test1Raj</opcode>
        <opcode>1</opcode>
        <opcode>Raj</opcode>
      </FBEN>
    </branch>
  </job>
</xmlexecute>

如果我试图添加

select
    'test' as 'job/branch/FBEN/opcode',
    users AS 'job/branch/FBEN/opcode',
    name as 'job/branch/FBEN/opcode',
    [1] AS 'job/branch/FBEN/opcode/1'   
from 
    @Table1
where 
    ts = 3
for xml path('xmlexecute'), elements;

我收到错误:

  

Msg 6850,Level 16,State 1,Line 14
  列名&#39; job / branch / FBEN / opcode / 1&#39;包含FOR XML所需的无效XML标识符; &#39; 1&#39;(0x0031)是第一个出错的角色。

1 个答案:

答案 0 :(得分:1)

试试这样:

DECLARE @Table1 TABLE (users int, ts int, name varchar(10), [1] int);

INSERT INTO @Table1 (users, ts, name, [1])
VALUES (1, 1, 'Raj', 0),
       (1, 3, 'maj', 2534),
       (1, 10, 'yes', 1458);
select
(
    select
        'test' as [opcode]
        ,''
        ,users AS [opcode]
        ,''
        ,name as [opcode] 
        ,''
        ,[1] AS [opcode]
    from 
        @Table1
    where 
        ts = 1
    for xml path('FBEN'),ROOT('branch'),TYPE
) AS job
FOR XML PATH('xmlexecute')
;

,''节点之间的空节点opcode告诉XML引擎:此节点已完成,启动一个新节点。如果要放置,则需要这样做几个名称相同的节点彼此相同。

结果

<xmlexecute>
  <job>
    <branch>
      <FBEN>
        <opcode>test</opcode>
        <opcode>1</opcode>
        <opcode>Raj</opcode>
        <opcode>0</opcode>
      </FBEN>
    </branch>
  </job>
</xmlexecute>