gpt4 book ai didi

sql - 将 XML 插入 SQL Server 表

转载 作者:数据小太阳 更新时间:2023-10-29 02:02:46 25 4
gpt4 key购买 nike

鉴于此 XML:

<Documents>
<Batch BatchID = "1" BatchName = "Fred Flintstone">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
<Document DocumentID = "299" KeyData = "" ImageFile="Test.TIF" />
</DocCollection>
</Batch>
<Batch BatchID = "2" BatchName = "Barney Rubble">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
</DocCollection>
</Batch>
</Documents>

我需要以这种格式将它插入到 SQL Server 中的表中:

BatchID   BatchName           DocumentID
1 Fred Flintstone 269
1 Fred Flintstone 6
1 Fred Flintstone 299
2 Barney Rubble 269
2 Barney Rubble 6

此 SQL:

   SELECT
XTbl.XCol.value('./@BatchID','int') AS BatchID,
XTbl.XCol.value('./@BatchName','varchar(100)') AS BatchName,
XTbl.XCol.value('DocCollection[1]/DocumentID[1]','int') AS DocumentID
FROM @Data.nodes('/Documents/Batch') AS XTbl(XCol)

得到这个结果:

BatchID BatchName       DocumentID
1 Fred Flintstone NULL
2 Barney Rubble NULL

我做错了什么?

此外,有人可以推荐一个很好的 SQL Server 中的 XML 教程吗?

谢谢

卡尔

最佳答案

你很接近。

使用通配符和 CROSS APPLY,您可以生成多条记录。

将别名更改为 lvl1lvl2 以更好地说明。

Declare @XML xml = '
<Documents>
<Batch BatchID = "1" BatchName = "Fred Flintstone">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
<Document DocumentID = "299" KeyData = "" ImageFile="Test.TIF" />
</DocCollection>
</Batch>
<Batch BatchID = "2" BatchName = "Barney Rubble">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
</DocCollection>
</Batch>
</Documents>
'

Select BatchID = lvl1.n.value('@BatchID','int')
,BatchName = lvl1.n.value('@BatchName','varchar(50)')
,DocumentID = lvl2.n.value('@DocumentID','int')
From @XML.nodes('Documents/Batch') lvl1(n)
Cross Apply lvl1.n.nodes('DocCollection/Document') lvl2(n)

返回

BatchID BatchName       DocumentID
1 Fred Flintstone 269
1 Fred Flintstone 6
1 Fred Flintstone 299
2 Barney Rubble 269
2 Barney Rubble 6

关于sql - 将 XML 插入 SQL Server 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45103755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com