将数据从用户定义的表类型转换为XML

时间:2014-09-09 02:49:25

标签: sql-server xml tsql sql-server-2012 user-defined-types

我有用户定义的表类型:

    CREATE TYPE [dbo].[t_data] AS TABLE(
      [nID] [numeric](20, 0) NOT NULL,
      [nLocationKey] [numeric](20, 0) NULL,
      [nMTkey] [numeric](20, 0) NULL
    )

需要像XML一样获取XML:

  <?xml version="1.0" encoding="utf-8"?>
  <LISTSAVE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <LIST>
            <ITEM>
                 <NMTKEY>1231</NMTKEY>
                 <NLOCATIONKEY>1123</NLOCATIONKEY>
            </ITEM>
            <ITEM>
                 <NMTKEY>7778</NMTKEY>
                 <NLOCATIONKEY>9999</NLOCATIONKEY>
            </ITEM>
       </LIST>
  </LISTSAVE>

我想创建一个从这个数据中生成xml的函数,如:

   CREATE FUNCTION [LOC_API].[wrapLocationData] (
       @in_oData dbo.t_data READONLY
       )
       RETURNS XML
       AS
    BEGIN
    DECLARE @l_cData XML
    /* Data to XML conversion */
    RETURN @l_cData
    END

1 个答案:

答案 0 :(得分:1)

XML查询没有什么不同,因为您使用的是表类型。

CREATE FUNCTION [dbo].[wrapLocationData]
(
  @in_oData dbo.t_data READONLY
) RETURNS XML AS
BEGIN
  DECLARE @l_cData XML;

  WITH XMLNAMESPACES(DEFAULT 'http://www.w3.org/2001/XMLSchema',
                     'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
  SELECT @l_cData = (
                    SELECT (
                           SELECT D.nMTkey AS NMTKEY,
                                  D.nLocationKey AS NLOCATIONKEY
                           FROM @in_oData AS D
                           FOR XML PATH('ITEM'), ROOT('LIST'), TYPE
                           )
                    FOR XML PATH('LISTSAVE'), TYPE
                    );

  RETURN @l_cData;
END

结果:

<LISTSAVE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema">
  <LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema">
    <ITEM>
      <NMTKEY>3</NMTKEY>
      <NLOCATIONKEY>2</NLOCATIONKEY>
    </ITEM>
    <ITEM>
      <NMTKEY>6</NMTKEY>
      <NLOCATIONKEY>5</NLOCATIONKEY>
    </ITEM>
  </LIST>
</LISTSAVE>

据我所知,没有理智的方法来避免双重命名空间声明。见How to remove xmlns from child elements with FOR XML