如何从sql 2008中的xml列中提取数据

时间:2012-03-07 11:11:08

标签: sql-server xml sql-server-2008 xquery-sql

我有一个包含xml类型列的表。我必须从xml列中提取值。我已经尝试了所有可能的方法,但我无法成功。请在下面找到xml数据的样本。

<Menu>
  <Id>1</Id>
    <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-1.jpg</Url>
</Menu>
<Menu>
  <Id>2</Id>
  <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-2.jpg</Url>
</Menu>
<Menu>
  <Id>3</Id>
  <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-3.jpg</Url>
</Menu>
<Menu>
  <Id>4</Id>
  <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-4.jpg</Url>
</Menu>
<Menu>
  <Id>5</Id>
  <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-5.jpg</Url>
</Menu>

请帮我提取数据。提前谢谢。

谢谢, Darthick。 s.darthick@gmail.com

2 个答案:

答案 0 :(得分:2)

declare @T table
(
  XMLCol xml
)

insert into @T values
('<Menu>
    <Id>1</Id>
      <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-1.jpg</Url>
  </Menu>
  <Menu>
    <Id>2</Id>
    <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-2.jpg</Url>
  </Menu>
  <Menu>
    <Id>3</Id>
    <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-3.jpg</Url>
  </Menu>
  <Menu>
    <Id>4</Id>
    <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-4.jpg</Url>
  </Menu>
  <Menu>
    <Id>5</Id>
    <Url>http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-5.jpg</Url>
  </Menu>')

select X.N.value('Id[1]', 'int') as Id,
       X.N.value('Url[1]', 'varchar(max)') as Url
from @T as T
  cross apply T.XMLCol.nodes('/Menu') as X(N)

结果:

Id          Url
----------- ---------------------------------------------------------------------
1           http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-1.jpg
2           http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-2.jpg
3           http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-3.jpg
4           http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-4.jpg
5           http://www.zmtcdn.com/menus/1211/menu-photo-for-barbeque-nation-5.jpg

答案 1 :(得分:1)

如果有命名空间。 XML:

<PersonInfo xmlns="http://mynamspace.lv/default">
    <Person ID="22">
        <Name>MyName</Name>
        <Profession>MyProfession</Profession>
    </Person>
</PersonInfo>

然后你应该做这样的事情:

WITH XMLNAMESPACES (DEFAULT 'http://mynamspace.lv/default')
SELECT
    @myXML.value('(PersonInfo/Person/@ID)[1]', 'nvarchar(100)') as ID,
    @myXML.value('(PersonInfo/Person/Name)[1]', 'nvarchar(100)') as Name,
    @myXML.value('(PersonInfo/Person/Profession)[1]', 'nvarchar(100)') as Profession;