15

我正在使用 T-SQL 从具有 XML 列的表中进行选择。我想选择某种类型的节点并为每个节点创建一行。

例如,假设我正在从人员表中进行选择。该表有一个地址的 XML 列。XML 的格式类似于以下内容:

<address>
  <street>Street 1</street>
  <city>City 1</city>
  <state>State 1</state>
  <zipcode>Zip Code 1</zipcode>
</address>
<address>
  <street>Street 2</street>
  <city>City 2</city>
  <state>State 2</state>
  <zipcode>Zip Code 2</zipcode>
</address>

我怎样才能得到这样的结果:

名称         城市         

乔·贝克 西雅图 WA

乔·贝克 塔科马 WA

弗雷德琼斯温哥华BC

4

5 回答 5

32

这是您的解决方案:

/* TEST TABLE */
DECLARE @PEOPLE AS TABLE ([Name] VARCHAR(20),  [Address] XML )
INSERT INTO @PEOPLE SELECT 
    'Joel', 
    '<address>
      <street>Street 1</street>
      <city>City 1</city>
      <state>State 1</state>
      <zipcode>Zip Code 1</zipcode>
    </address>
    <address>
      <street>Street 2</street>
      <city>City 2</city>
      <state>State 2</state>
      <zipcode>Zip Code 2</zipcode>
    </address>'
UNION ALL SELECT
    'Kim', 
    '<address>
      <street>Street 3</street>
      <city>City 3</city>
      <state>State 3</state>
      <zipcode>Zip Code 3</zipcode>
    </address>'

SELECT * FROM @PEOPLE

-- BUILD XML
DECLARE @x XML
SELECT @x = 
( SELECT 
      [Name]
    , [Address].query('
            for $a in //address
            return <address 
                street="{$a/street}" 
                city="{$a/city}" 
                state="{$a/state}" 
                zipcode="{$a/zipcode}" 
            />
        ') 
  FROM @PEOPLE AS people 
  FOR XML AUTO
) 

-- RESULTS
SELECT [Name]    = T.Item.value('../@Name', 'varchar(20)'),
       street    = T.Item.value('@street' , 'varchar(20)'),
       city      = T.Item.value('@city'   , 'varchar(20)'),
       state     = T.Item.value('@state'  , 'varchar(20)'),
       zipcode   = T.Item.value('@zipcode', 'varchar(20)')
FROM   @x.nodes('//people/address') AS T(Item)

/* OUTPUT*/

Name | street   | city   | state   | zipcode
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Joel | Street 1 | City 1 | State 1 | Zip Code 1
Joel | Street 2 | City 2 | State 2 | Zip Code 2
Kim  | Street 3 | City 3 | State 3 | Zip Code 3
于 2008-10-11T04:11:04.857 回答
1

这是我一般的做法:

我通过调用粉碎了源 XML,例如



DECLARE @xmlEntityList xml
SET @xmlEntityList =
'
<ArbitrarilyNamedXmlListElement>
              <ArbitrarilyNamedXmlItemElement><SomeVeryImportantInteger>1</SomeVeryImportantInteger></ArbitrarilyNamedXmlItemElement>
              <ArbitrarilyNamedXmlItemElement><SomeVeryImportantInteger>2</SomeVeryImportantInteger></ArbitrarilyNamedXmlItemElement>
              <ArbitrarilyNamedXmlItemElement><SomeVeryImportantInteger>3</SomeVeryImportantInteger></ArbitrarilyNamedXmlItemElement>
</ArbitrarilyNamedXmlListElement>
'

    DECLARE @tblEntityList  TABLE(
        SomeVeryImportantInteger    int
    )

    INSERT @tblEntityList(SomeVeryImportantInteger)
    SELECT 
        XmlItem.query('//SomeVeryImportantInteger[1]').value('.','int') as SomeVeryImportantInteger
    FROM
        [dbo].[tvfShredGetOneColumnedTableOfXmlItems] (@xmlEntityList)



通过利用标量值函数


/* Example Inputs */
/*
DECLARE @xmlListFormat xml
SET     @xmlListFormat =
            '
            <ArbitrarilyNamedXmlListElement>
              <ArbitrarilyNamedXmlItemElement>004421UB7</ArbitrarilyNamedXmlItemElement>
              <ArbitrarilyNamedXmlItemElement>59020UH24</ArbitrarilyNamedXmlItemElement>
              <ArbitrarilyNamedXmlItemElement>542514NA8</ArbitrarilyNamedXmlItemElement>
            </ArbitrarilyNamedXmlListElement>
            '
declare @tblResults TABLE 
(
    XmlItem xml
)

*/

-- =============================================
-- Author:      6eorge Jetson
-- Create date: 01/02/3003
-- Description: Shreds a list of XML items conforming to
--              the expected generic @xmlListFormat
-- =============================================
CREATE FUNCTION [dbo].[tvfShredGetOneColumnedTableOfXmlItems]  
(
    -- Add the parameters for the function here
    @xmlListFormat xml
)
RETURNS 
@tblResults TABLE 
(
    -- Add the column definitions for the TABLE variable here
    XmlItem xml
)
AS
BEGIN

    -- Fill the table variable with the rows for your result set
    INSERT @tblResults
    SELECT
        tblShredded.colXmlItem.query('.')   as XmlItem
    FROM
         @xmlListFormat.nodes('/child::*/child::*') as tblShredded(colXmlItem)

    RETURN 
END

--SELECT * FROM @tblResults


于 2008-10-11T21:15:13.260 回答
0

如果这对寻找“通用”解决方案的其他人有用,我创建了一个 CLR 过程,它可以采用上述 Xml 片段并将其“分解”到表格结果集中,而无需您提供有关名称的任何其他信息或列的类型,或以任何方式为给定的 Xml 片段自定义调用:

http://architectshack.com/ClrXmlShredder.ashx

当然有一些限制(xml 必须像这个示例一样本质上是“表格”,第一行需要包含将支持的所有元素/列等) - 但我确实希望它比现在的可用的内置。

于 2011-06-19T21:50:44.123 回答
0

这是一个替代解决方案:

;with cte as 
(
    select id, name, addresses, addresses.value('count(/address/city)','int') cnt
    from @demo
)
, cte2 as
(
    select id, name, addresses, addresses.value('((/address/city)[sql:column("cnt")])[1]','nvarchar(256)') city, cnt-1 idx 
    from cte 
    where cnt > 0

    union all

    select cte.id, cte.name, cte.addresses, cte.addresses.value('((/address/city)[sql:column("cte2.idx")])[1]','nvarchar(256)'), cte2.idx-1 
    from cte2 
    inner join cte on cte.id = cte2.id and cte2.idx > 0
)
select id, name, city 
from cte2 
order by id, city

仅供参考:我在代码审查网站上发布了此 SQL 的另一个版本:https ://codereview.stackexchange.com/questions/108805/select-field-in-an-xml-column-where-both-xml- and-table-contain-multiple-matches

于 2015-10-26T20:46:10.350 回答
-4

如果可以使用,linq api 对 XML 来说很方便:

var addresses = dataContext.People.Addresses
    .Elements("address")
        .Select(address => new { 
            street  = address.Element("street").Value, 
            city    = address.Element("city").Value, 
            state   = address.Element("state").Value, 
            zipcode = address.Element("zipcode").Value, 
        });
于 2008-10-10T17:52:23.513 回答