如何在不重复两次字段的情况下生成XML

时间:2016-11-08 22:24:18

标签: sql-server xml

我正在尝试使用以下代码生成xml。但我对输出结果不满意。在代码下面,我使用游标来获取要生成的xml的ID并在另一个表中更新。任何帮助表示赞赏,我是xml的新手。感谢

DECLARE @xml_var XML;
DECLARE @ID INT;
DECLARE XML_CURSOR CURSOR FOR
    SELECT id
    FROM   xml_temp_table
    WHERE  id IS NOT NULL;

OPEN XML_CURSOR;
FETCH NEXT
    FROM  XML_CURSOR
    INTO  @ID;

WHILE @@FETCH_STATUS = 0
BEGIN
  SET @xml_var =
  (
         SELECT
                (
                       SELECT 'Type'    AS ID,
                              'Initial' AS VALUE,
                              ''        AS TAG,
                              'true'    AS VISIBLE,
                              Getdate() AS HISTORY,
                              ''        AS DESCRIPTION,
                              ''        AS COMMENT
                       FROM   XML_TABLE d
                       WHERE  D.XML_ID = @ID FOR XML PATH('field'),
                              TYPE ) AS 'field',
                (
                       SELECT 'OwnerName'   AS ID,
                              'Testing_XML' AS VALUE,
                              ''            AS TAG,
                              'true'        AS VISIBLE,
                              Getdate()     AS HISTORY,
                              ''            AS DESCRIPTION,
                              ''            AS COMMENT
                       FROM   XML_TABLE d
                       WHERE  D.XML_ID = @ID FOR XML PATH('field'),
                              TYPE ) AS 'field'
         FROM   XML_TABLE p
         WHERE  P.XML_ID = @ID FOR XML PATH('Material'),
                ROOT('FormValue') );
  UPDATE S
  SET    S.XML_COL = @xml_var,
  FROM   LOCATION_TABLE_XML S
  WHERE  S.ID = @ID;

  FETCH NEXT
      FROM  XML_CURSOR
      INTO  @ID;

END; 

我得到的结果就是这样

 <FormValue>
<Material>
 <field> ----- i dont want this
  <field>
    <id>Type</id>
    <value>Initial</value>
    <tag />
    <visible>true</visible>
    <history>2016-11-08T16:53:16.440</history>
    <description />
    <comment />
  </field>
  <field>
    <id>OwnerName</id>
    <value>Testing_XML</value>
    <tag />
    <visible>true</visible>
    <history>2016-11-08T16:53:16.440</history>
    <description />
    <comment />
  </field>
</field> ---- i dont want this
 </Material>
</FormValue>

但我想以这种方式得到结果

 <FormValue>
 <Material>
  <field>
    <id>Type</id>
    <value>Initial</value>
    <tag />
    <visible>true</visible>
    <history>2016-11-08T16:53:16.440</history>
    <description />
    <comment />
  </field>
  <field>
    <id>OwnerName</id>
    <value>Testing_XML</value>
    <tag />
    <visible>true</visible>
    <history>2016-11-08T16:53:16.440</history>
    <description />
    <comment />
  </field>
  </Material>
  </FormValue>

1 个答案:

答案 0 :(得分:2)

可能足以让AS 'field'离开。您的FOR XML PATH('field')将使用<field>元素包装每一行。

XML返回子选择可以看作是像普通列一样处理的标量值。通过提供列别名,整个节点获得一个名称,并将此名称再次转换为包装<field>元素。

您可以将其删除,或将其替换为AS [node()]AS [*]