使用SQL Server XML导入添加索引

时间:2018-09-07 14:09:00

标签: sql sql-server xml xml-parsing

在SQL Server中,我尝试使用XML函数来导入文件,如下所示:

SELECT 
    file.value('@registrationnumber[1]', 'nvarchar(100)') AS [registrationnumber],
    report.value('@nihil[1]', 'nvarchar(100)') AS [nihil],
    report.value('@period[1]', 'nvarchar(100)') AS [period],
    report.value('@formulaid[1]', 'nvarchar(100)') AS [formulaid],
    report.value('@frequention[1]', 'nvarchar(100)') AS [frequention],
    report.value('@versieon[1]', 'nvarchar(100)') AS [version],
    variant.value('@type[1]', 'nvarchar(100)') AS [varianttype],
    variant.value('@value[1]', 'nvarchar(100)') AS [variantvalue],
    post.value('@cube[1]', 'nvarchar(100)') AS [cube],
    post.value('@row[1]', 'nvarchar(100)') AS [row],
    post.value('@rownr[1]', 'nvarchar(100)') AS [rownr],
INTO
    [#parsed]
FROM
    @xmlData.nodes('file') AS a(file)
CROSS APPLY
    file.nodes('report') AS b(report)
CROSS APPLY
    report.nodes ('post') AS c(post)
OUTER APPLY
    report.nodes ('variant') AS d(variant)

我想知道是否有可能自动为加载的每个报告添加具有唯一索引的附加列。

我无法在Google上找到解决方案,因为我认为我使用了错误的搜索字词。

1 个答案:

答案 0 :(得分:0)

使用ROW_NUMBER()

SELECT 
    file.value('@registrationnumber[1]', 'nvarchar(100)') AS [registrationnumber],
    report.value('@nihil[1]', 'nvarchar(100)') AS [nihil],
    report.value('@period[1]', 'nvarchar(100)') AS [period],
    report.value('@formulaid[1]', 'nvarchar(100)') AS [formulaid],
    report.value('@frequention[1]', 'nvarchar(100)') AS [frequention],
    report.value('@versieon[1]', 'nvarchar(100)') AS [version],
    variant.value('@type[1]', 'nvarchar(100)') AS [varianttype],
    variant.value('@value[1]', 'nvarchar(100)') AS [variantvalue],
    post.value('@cube[1]', 'nvarchar(100)') AS [cube],
    post.value('@row[1]', 'nvarchar(100)') AS [row],
    post.value('@rownr[1]', 'nvarchar(100)') AS [rownr],
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) YourSequentialIndex
INTO
    [#parsed]
FROM
    @xmlData.nodes('file') AS a(file)
        CROSS APPLY
    file.nodes('report') AS b(report)
        CROSS APPLY
    report.nodes ('post') AS c(post)
        OUTER APPLY
    report.nodes ('variant') AS d(variant)