如何在 SQL 服务器中使用 for XML 合并节点并中断新值

How to combine nodes and break on new values using for XML in SQL Server

在下面的示例中,我需要一个 FOR XML 查询来说明 actionswords 何时相同,然后将 content 合并到一个节点下。

目前我有这个:

   <Actionword actionword="Bangs">
       <Content>Your heavy swing forces something to break off your opponent and snaps past you through the air...</Content>
   </Actionword>
   <Actionword actionword="Bangs">
       <Content>...a crushing overhand strike leaves your foe both broken and defeated.</Content>
   </Actionword>
   <Actionword actionword="Bangs">
       <Content>...a crushing overhand strike leaves your foe both broken and defeated.</Content>
   </Actionword>

(注意如何在每个<content>节点之间有一个<Actionword>节点。即使动作词相同。

我需要这个:

<Actionword actionword="Bangs">
    <Content>Your heavy swing forces something to break off your opponent and snaps past you through the air...</Content>
    <Content>...a crushing overhand strike leaves your foe both broken and defeated.</Content>
    <Content>...a crushing overhand strike leaves your foe both broken and defeated.</Content>
</Actionword>

我的来源 table 是非规范化的,并为每个不同的 content 存储一个新行。

table 结构只是两个字段,Actionword (nvarchar(max)) 和 [Content] (nvarchar(max))。

您应该在主查询中对 actionword 进行分组,并在 actionword 相关的列列表中获取相关子查询中的 Content 节点。

select T1.Actionword as [@actionword],
       (
       select T2.Content
       from dbo.YourTable as T2
       where T1.Actionword = T2.Actionword
       for xml path(''), type
       )
from dbo.YourTable as T1
group by T1.Actionword
for xml path('Actionword');