SQL 通过分组和嵌套将数据保存到 XML 列

SQL save data into XML column with grouping and nesting

我在将数据从 table 保存到 xml

时遇到问题,如下所示
ID  personID  Type   Name   category  value
1     1234    xtype   John     abc      200
2     1234    ytype   John     xyz      230
3     1234    ztype   John     ccc      220
4     2222    xtype   Jim      abc      200

我需要将以上数据保存在 xml 条件。

Data of personId 1234 is having 3 rows of data with three different types(x,yz) so all these three rows of data should be saved in one xml datatype, > column with different personID 2222 should store in next row, it only has one type(x) so it will have only once.

需要xml示例

<Data>
<PersonID>1234</PersonID>
<SpecifiedType>
<Type>xtype</Type>
<Name>John</Name>
<category>abc</category>
<value>200</Value>
</SpecifiedType>
<SpecifiedType>
<Type>Ytype</Type>
<Name>John</Name>
<category>xyz</category>
<value>230</Value>
</SpecifiedType>
 <SpecifiedType>
 <Type>Ztype</Type>
 <Name>John</Name>
 <category>ccc</category>
 <value>220</Value>
 </SpecifiedType>
 </Data>

根据它应该分组的类型,有时 personID 将只有一种类型。

我能够将单行数据生成到 xml 但无法以上述格式存储它。

您可以使用 FOR XML 执行此操作。为了得到你想要的分组和结构涉及几层但并不难;

declare @t table (ID int, PersonID int, Type varchar(10), Name varchar(10), category varchar(10), value int)
insert @t values
    (1, 1234, 'xtype', 'John', 'abc', 200),
    (2, 1234, 'ytype', 'John', 'xyz', 230),
    (3, 1234, 'ztype', 'John', 'ccc', 220),
    (4, 2222, 'xtype', 'Jim', 'abc', 200)

; with cte
as (
    select distinct PersonID from @t
)
select
    (select
        PersonID,
        (select
             Type,
             Name,
             category,
             value
         from
             @t t
         where
             t.PersonID = cteInner.PersonID
         for xml path('SpecifiedType'), type ) 
    from
        cte cteInner
    where
        cteInner.PersonID = cteOuter.PersonID
    for xml path(''), type, root('data') )
from 
    cte cteOuter