【发布时间】:2020-11-10 15:14:06
【问题描述】:
我需要解析下面的 XML 并在结果集中为每个 Example_Code 或 Body_text 创建一个新行 - 这些元素可以以任何顺序存在,我正在尝试创建一个如下表所示的结果集。
declare @Xml xml = '
<Demonstrative_Examples>
<Demonstrative_Example>
<Intro_Text>
This is the intro
</Intro_Text>
<Example_Code Nature="bad" >
Example 1.1
</Example_Code>
<Body_Text>Body 1.1</Body_Text>
<Example_Code>
Example 1.2
</Example_Code>
</Demonstrative_Example>
<Demonstrative_Example>
<Intro_Text>
This is the 2nd intro
</Intro_Text>
<Body_Text>Body 2.1</Body_Text>
<Example_Code Nature="Good">
Example 2.1
</Example_Code>
</Demonstrative_Example>
</Demonstrative_Examples>'
SELECT 1 as 'Demonstrative_Example_ID',
1 as 'OrderID',
DemonstrativeExample.x.value('(Intro_Text)[1]','nvarchar(4000)') AS 'Intro_Text',
Body.x.value('.','nvarchar(4000)') AS 'Body_Text',
ExampleCode.x.value('.','varchar(200)') AS 'Example_Code',
ExampleCode.x.value('(@Nature)[1]','nvarchar(100)') AS 'Example_CodeNature'
FROM @Xml.nodes('//Demonstrative_Examples/Demonstrative_Example') AS DemonstrativeExample(x)
OUTER APPLY DemonstrativeExample.x.nodes('./Body_Text') AS Body(x)
OUTER APPLY DemonstrativeExample.x.nodes('./Example_Code') AS ExampleCode(x)
使用上面的 T-SQL 我想返回一个结果集如下:
谁能建议如何修改 T-SQL 以获得预期的结果集?
【问题讨论】:
标签: sql-server xml xquery