将 XML 转换为 table SQL Server 2005

Convert XML to table SQL Server 2005

我想知道如何读取 XML 数据并将其转换为 T-SQL 中的 table?

例如:

<t1>
      <t2>
        <val>Opel</val>
        <t3>Merriva</t3>
        <t3>Zafira</t3>
      </t2>
      <t2>
        <val>Fiat</val>
        <t3>Albea</t3>
      </t2>
  </t1>

收件人:

表 1:

id      value
----------------
1        Opel
2        Fiat

表 2:

id      id_Table1       value
-----------------------------------
1          1            Merriva
2          1            Zafira
3          2            Albea

我没有活动的 SQL-Server 2005 来测试这个(男孩,现在是 2018 年......!!!),但我认为这个查询也适用于如此古老的版本:

DECLARE @xml XML=
N'<t1>
    <t2>
    <val>Opel</val>
    <t3>Merriva</t3>
    <t3>Zafira</t3>
    </t2>
    <t2>
    <val>Fiat</val>
    <t3>Albea</t3>
    </t2>
</t1>';

--The CTE will return the CarName with a running index together with the related data as XML-node
WITH Cars AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS t2_index
        ,t2.value(N'(val/text())[1]',N'nvarchar(100)') AS t2_val
        ,t2.query(N't3') AS t3_nodes
    FROM @xml.nodes(N'/t1/t2') A(t2)
)
--This part will append all related data with a running number for the related type data
SELECT Cars.* 
    ,ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) AS CarValueIndex
    ,t3.value(N'text()[1]',N'nvarchar(100)') AS CarValue
INTO #tmpCars --write the result into a temp table
FROM Cars
OUTER APPLY t3_nodes.nodes(N't3') A(t3);

--All data de-normalized
SELECT * FROM #tmpCars;

--This query will bring back the parent rows
SELECT t2_index AS CarID
      ,t2_val AS CarName
FROM #tmpCars
GROUP BY t2_index,t2_val;

--And this query will return the related child data
SELECT CarValueIndex AS CarTypeID
      ,t2_index AS fk_CarID
      ,CarValue AS CarType
FROM #tmpCars;

GO
DROP TABLE #tmpCars;

如果有任何机会迁移到更现代的 SQL-服务器,您真的应该这样做...

更新

根据this link,v2008 引入了.value().nodes() 函数。但我有一个黑暗的记忆,它已经在 2005 年工作,可能与一些服务包一起...试试看。