即使没有记录,也在SQL中生成空xml根节点

时间:2016-08-10 11:20:49

标签: sql xml sql-server-2008

我在从sql生成空\ null xml根节点时遇到问题。这是我正在研究的结构的一个例子:

<Departments>
    <Department>
        <Employees>
         <Employee>
            <Name></Name>
            <ID></ID>
         </Employee>
        </Employees>
    </Department>
    </Departments>

下面是我用来生成结构的sql:

declare @Employee table (Name varchar(50), ID int, DID int)
declare @Department table (Name varchar(50), DID int)
declare @xmldata xml

insert into @Employee values ('AAA', 1, 3)
insert into @Employee values ('BBB', 2, 3)
--insert into @Department values ('CCC', 3)

SET @xmldata = 
(

select GETDATE() as 'ReportDate', (

select D.Name,
(
select (
       select E.Name,
              E.ID
       from @Employee E
    where E.DID = D.DID
       for xml path ('Employee'), elements xsinil, type    
       )
for xml path('Employees'), type
)
from @Department D
for xml path('Department'), type
)

for xml path ('Departments'), type
)
select @xmldata

如果有记录,xml结构正常,但问题是如果没有部门记录,根本就没有节点。如何在xml中至少显示空节点?

如果没有部门记录,xml将是:

<Departments>
  <ReportDate>2016-08-11T16:31:22.960</ReportDate>
</Departments>

我喜欢的是:

<Departments>
  <ReportDate>2016-08-11T16:31:22.960</ReportDate>
  <Department />
</Departments>

2 个答案:

答案 0 :(得分:0)

我了解了你的问题。您可以尝试以下概念。

SELECT ISNULL(s.lmx, '<Users></Users>')
FROM 
    (
        select 1 as tag, null as parent,
        FirstName as [User!1!FirstName!Element],
        LastName as [User!1!LastName!Element]
        FROM Users
        FOR XML EXPLICIT
    ) AS s(lmx)

我也遇到了同样的问题,我从here

得到了提示

答案 1 :(得分:0)

使用包含1行的派生表,并针对@Departments执行外部应用。

select getdate() as ReportDate,
       (
       select D.Name,
              isnull(D.Employees, '') as Employees
       from (select null) as T(N)
         outer apply (
                     select D.Name,
                            (
                            select E.Name,
                                   E.ID
                            from @Employee E
                            where E.DID = D.DID
                            for xml path ('Employee'), elements xsinil, type    
                            ) as Employees
                     from @Department as D
                     ) as D
       for xml path('Departments'), type
       )
for xml path('Departments'), type