将XML数据放入表中

时间:2012-07-27 06:29:16

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

我有以下XML

<Queue>
    <UserName>UserName</UserName>
    <Type>1</Type>
    <Portal name="Portal1">
        <IndexesForSelect>
            <Index>Index1</Index>
            <Index>Index2</Index>
        </IndexesForSelect>
    </Portal>
    <Portal name="Portal2">
        <IndexesForSelect>
            <Index>Index3</Index>
            <Index>Index4</Index>
        </IndexesForSelect>
    </Portal>
</Queue>

我需要将它以格式

的形式提供给一个表格
Portal      Index
---------------------------
Portal1     Index1
Portal1     Index2
Portal2     Index3
Portal2     Index4

如果有人能帮助我,我真的很感激。

我尝试了以下代码,但它只返回每Index

的第一个Portal
declare @T table
(
  XMLCol xml
)

insert into @T values
('<Queue>
      <UserName>UserName</UserName>
      <Type>1</Type>
      <Portal name="Portal1">
        <IndexesForSelect>
          <Index>Index1</Index>
          <Index>Index2</Index>
        </IndexesForSelect>
      </Portal>
      <Portal name="Portal2">
        <IndexesForSelect>
          <Index>Index3</Index>
          <Index>Index4</Index>
        </IndexesForSelect>
      </Portal>
    </Queue>')
SELECT  items.value('../@name','varchar(max)') AS [Portal],
        items.value('(Index)[1]','varchar(max)') AS [Index]
FROM @T AS T CROSS APPLY T.XMLCol.nodes('Queue/Portal/IndexesForSelect') c (items)

2 个答案:

答案 0 :(得分:1)

select T1.N.value('@name', 'varchar(max)') as Portal,
       T2.N.value('.', 'varchar(max)') as [Indes]
from @T as T
  cross apply XMLCol.nodes('/Queue/Portal') as T1(N)
  cross apply T1.N.nodes('IndexesForSelect/Index') as T2(N)

答案 1 :(得分:0)

尝试使用SQL管理工作室提供的导出/导入功能。

阅读相关内容Go here