gpt4 book ai didi

sql-server - 从 SQL Server 中的 XML 读取子节点及其父属性

转载 作者:行者123 更新时间:2023-12-02 04:20:27 25 4
gpt4 key购买 nike

我有一个与此结构类似的 XML。

<Root>
<id>a2bh5</id>
<Student ID="123">
<Name>abc<Name>
<course>ETL<course>
<Scores>
<Score>
<Subject>SSIS<subject>
<grade>B<grade>
</score>
<Score>
<Subject>Informatica<subject>
<grade>C<grade>
</score>
</Scores>
</Student>
<Student ID="456">
<Name>xyz<Name>
<course>ETL<course>
<Scores>
<Score>
<Subject>Pentaho<subject>
<grade>F<grade>
</score>
<Score>
<Subject>Datastage<subject>
<grade>A<grade>
</score>
</Scores>
</Student>
</Root>

我想在 SQL Server 中使用 Xquery 获取子节点(分数)及其父属性(Id)的详细信息。

所有主题的查询结果预计如下。请帮忙。

Student_Id subject grade
========================
123 SSIS B

最佳答案

清理示例 XML 并正确关闭所有标记后,请尝试以下操作:

DECLARE @input XML = '<Root>
<id>a2bh5</id>
<Student ID="123">
<Name>abc</Name>
<course>ETL</course>
<Scores>
<Score>
<Subject>SSIS</Subject>
<grade>B</grade>
</Score>
<Score>
<Subject>Informatica</Subject>
<grade>C</grade>
</Score>
</Scores>
</Student>
<Student ID="456">
<Name>xyz</Name>
<course>ETL</course>
<Scores>
<Score>
<Subject>Pentaho</Subject>
<grade>F</grade>
</Score>
<Score>
<Subject>Datastage</Subject>
<grade>A</grade>
</Score>
</Scores>
</Student>
</Root>'

SELECT
StudentID = XStudents.value('@ID', 'int'),
Course = XStudents.value('(course)[1]', 'varchar(50)'),
Subject = XScore.value('(Subject)[1]', 'varchar(50)'),
Grade = XScore.value('(grade)[1]', 'varchar(10)')
FROM
@Input.nodes('/Root/Student') AS XT1(XStudents)
CROSS APPLY
XStudents.nodes('Scores/Score') AS XT2(XScore)

这给出了输出:

enter image description here

关于sql-server - 从 SQL Server 中的 XML 读取子节点及其父属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30869346/

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