没有selfclosing嵌套nat的mssql xml

时间:2018-04-23 08:58:30

标签: sql-server xml

这可能是一个非常愚蠢的问题,但我是一个关于mssql语言的本机xml指令的完整菜鸟。

场景如下:将有一个父表和一个子表。父亲1将有0个孩子,而父亲2将有2个孩子。

所以,我生成的xml(到目前为止)是

<RootNode>
    <Father>
        <my_column_one>0</my_column_one>
        <Children />               <--- !!!!!! How can i get rid of this???
    </Father>
    <Father>
         <my_column_one>2</my_column_one>
         <Children>
             <Child>
                 <my_column_two>b</my_column_two>
             </Child>
             <Child>
                 <my_column_two>c</my_column_two>
             </Child>
         </Children>
    </Father>
</RootNode>

如何摆脱父1空的<Children/>标签?

我创建了一个sqlfiddle:http://sqlfiddle.com/#!18/99284/1

到目前为止,我的查询是

select
(
    SELECT FATHER.col_one AS my_column_one,
    (
        SELECT
        (
            SELECT CHILD.col_two AS my_column_two
            FROM   EIAC.EIAC.xml_debug_child CHILD
            WHERE  FATHER.col_one = CHILD.col_one
            FOR XML PATH('Child'),TYPE
        )
        FOR XML PATH('Children'),TYPE
    )
    FROM EIAC.EIAC.xml_debug_father FATHER
    for xml path('Father'), type
)
for xml path('RootNode')

非常感谢你!!!

1 个答案:

答案 0 :(得分:1)

这可以很容易地完成:

DECLARE @t1 TABLE(id INT IDENTITY, col_one VARCHAR(100));
INSERT INTO @t1 VALUES('Father 1'),('Father 2');

DECLARE @t2 TABLE(id INT IDENTITY, father_id INT, col_two VARCHAR(100));
INSERT INTO @t2 VALUES(2,'Child 1'),(2,'Child 2');

select
(
    SELECT FATHER.col_one AS my_column_one,
        (
            SELECT CHILD.col_two AS my_column_two
            FROM   @t2 CHILD
            WHERE  FATHER.id = CHILD.father_id
            FOR XML PATH('Child'),TYPE
        ) AS [Children]
    FROM @t1 FATHER
    for xml path('Father'), type
)
for xml path('RootNode');

您将相关子查询包装在其他子查询FOR XML PATH中,但您只需通过命名返回的列即可添加嵌套级别<children>。如果没有,你将看不到元素。