开发者社区> 问答> 正文

SQL Server表嵌套的xml文件

SQL Server表嵌套的xml文件

展开
收起
贺贺_ 2019-12-05 23:30:08 438 0
1 条回答
写回答
取消 提交回答
  • 感谢@Isaac提供的数据脚本!

    for <List> elements in <Branch> node, like <Branch><List/><List/></Branch>:
    
    CREATE TABLE #mytable
    (
       Action  VARCHAR(10),
       Action2 VARCHAR(10),
       Name    VARCHAR(50),
       Action3 VARCHAR(10),
       Batch   INT
    );
    
    INSERT INTO #mytable(Action,Action2,Name,Action3,Batch) 
    VALUES 
    ('add','PL','Steve','add',1),
    ('add','PL','Steve','add',3),
    ('add','PL','Steve','add',4),
    ('add','PL','Steve','add',5),
    ('add','PL','Steve','add',1),
    ('add','PL','Steve','add',3),
    ('add','PL','Steve','add',4),
    ('add','PL','Steve','add',5);
    
    
    INSERT INTO #mytable(Action,Action2,Name,Action3,Batch) 
    VALUES 
    ('update','PL','John','insert',5),
    ('update','PL','Paul','insert',1),
    ('update','PL','Chris','delete',3),
    ('update','PL','Mary','update',4),
    ('update','PL','Jane','delete',5);
    
    
    select a1.Action as '@Action', s.brancexml as '*'
    from
    (
    select distinct Action
    from #mytable
    ) as a1
    cross apply 
    (
        select
        (
            select a2.Action2 AS '@Action', a2.Name as '@Name', x.listxml as     '*'
            from
        (
            select distinct Action2, Name
            from #mytable AS b
            where b.Action = a1.Action
        ) AS a2
        cross apply
        (
            select
            (
                select distinct c.Action3 as '@Action', c.Batch as '@Batch'
                from #mytable AS c
                where c.Action = a1.Action AND c.Action2 = a2.Action2 AND c.Name = a2.Name
                for xml path('List'), type
            ) AS listxml
        ) as x
        for xml path('Brance'), type
        ) as brancexml
    ) as s
    for xml path('Start'), root('Entries'), type
    
    2019-12-05 23:31:08
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server 2017 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载