从xml列填充子表

时间:2017-09-19 15:11:04

标签: xml sql-server-2008

我的xml看起来像这样,存储在表格中:Files:

#standardSQL
SELECT SUM(qty) AS sum, _TABLE_SUFFIX AS table 
FROM `black-resource-174911.owner.sales2017*`
WHERE category = 'shoes'
GROUP BY table  

如果我设置的表格如下:

<file>
    <collections>
        <collection>
            <date>1-1-2017</date>
            <codes>
                 <identifier>A</identifier>
                 <date>A</date>
            </codes>
        </collection>
        ...More collections here
    </collections>
</file>

有没有办法从Files&gt;查询xmlData到两个子表中,它以正确索引外键的方式填充子表?

1 个答案:

答案 0 :(得分:1)

首先:永远不会使用与文化相关的日期格式!您的1-1-2017将在其他地方成为2-3-2017。是三月的第二天还是二月的三月?始终在XML中使用ISO8601。在您的情况下2017-01-01YYYY-MM-DD

试试这个

DECLARE @xml XML=
N'<file>
    <collections>
        <collection>
            <date>2017-01-01</date>
            <codes>
                 <identifier>A</identifier>
                 <date>A</date>
            </codes>
        </collection>
        <collection>
            <date>2017-02-03</date>
            <codes>
                 <identifier>B</identifier>
                 <date>B</date>
            </codes>
        </collection>
    </collections>
</file>';

- 查询

WITH files AS
(
    SELECT  ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS FileId
           ,Fl.query('.') AS xmlData
    FROM @xml.nodes(N'/file') AS A(Fl)
)
,collections AS
(
    SELECT files.FileId
          ,files.xmlData
          ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS CollectionId
          ,col.value(N'(date/text())[1]',N'date') AS CollectionDate
          ,col.query(N'codes') AS optionXml
    FROM files
    OUTER APPLY files.xmlData.nodes(N'/file/collections/collection') AS A(col)
)
SELECT   collections.FileId
        ,collections.xmlData
        ,collections.CollectionId
        ,collections.CollectionDate
        ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS CodeId
        ,col.value(N'(identifier/text())[1]',N'nvarchar(max)') AS CodeIdentifier
        ,col.value(N'(date/text())[1]',N'nvarchar(max)') AS CodeDate
FROM collections
OUTER APPLY collections.optionXml.nodes(N'/codes') AS A(col);

将其写入临时表并使用SELECT DISTINCT将每组数据与相应的外键一起插入其表中。