选择XML节点作为行

时间:2008-10-10 17:37:03

标签: sql xml tsql xpath

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

例如,假设我从 people 表中进行选择。此表具有地址的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>

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

命名 城市 国家

Joe Baker Seattle WA

Joe Baker Tacoma WA

弗雷德琼斯温哥华不列颠哥伦比亚省

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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


答案 2 :(得分:0)

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

http://architectshack.com/ClrXmlShredder.ashx

当然有一些限制(xml必须是“表格式”,就像这个样本一样,第一行需要包含将支持的所有元素/列等) - 但我希望它只是几个步骤在内置的内容之前。

答案 3 :(得分: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

答案 4 :(得分:-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, 
        });