如何在for xml select中添加包装元素?

时间:2017-01-26 17:48:14

标签: sql-server sql-server-2008-r2 for-xml

我想改进我在Control on XML elements nesting using FOR XML

中所做的示例

我想添加一个包装所有元素的元素(在这个例子中,信息是关于公司的。)

DATA:

DECLARE @Employees table(
    CompanyID int,
    companyDescr nvarchar(100)  ,
    EmpID int NOT NULL,  
    Name nvarchar(50),  
    Surname nvarchar(50),  
    DateOfBirth date,
    DepartmentID int,
    AccessLevel int);
insert into  @Employees    values (1,'ACME','1', 'John','Doe','1980-01-31',100,5)
insert into  @Employees    values (1,'ACME', '2', 'Mary','Rose','1971-02-27',102,3)
insert into  @Employees    values (1,'ACME', '3', 'Luke','Perry','1995-12-01',104,1)

预期结果:

<company companyID="1">
    <employee Name="John" Surname="Doe" DateOfBirth="1980-01-31">
      <department DepartmentID="100">
        <security>
          <AccessLevel>5</AccessLevel>
        </security>
      </department>
    </employee>
    <employee Name="Mary" Surname="Rose" DateOfBirth="1971-02-27">
      <department DepartmentID="102">
        <security>
          <AccessLevel>3</AccessLevel>
        </security>
      </department>
    </employee>
    <employee Name="Luke" Surname="Perry" DateOfBirth="1995-12-01">
      <department DepartmentID="104">
        <security>
          <AccessLevel>1</AccessLevel>
        </security>
      </department>
    </employee>
</company>

如何查询@employees表以获取结果?

我找到的唯一方法是将链接问题的查询保存到字符串变量中,并在其前后手动追加数据。

是否可以通过查询来实现结果?

1 个答案:

答案 0 :(得分:0)

您可以像这样关联companyId上的子查询:

select
    companyid as "@companyID",
    cast((
        select name as "@Name",
            surname as "@Surname",
            dateofbirth as "@DateOfBirth",
            departmentid as "department/@departmentID",
            accesslevel as "department/security/AccessLevel"
        from @employees e2
        where e2.companyid = e1.companyid
        for xml path('employee')
    ) as xml)
from @employees e1
group by companyid for xml path('company');

产地:

<company companyID="1">
  <employee Name="John" Surname="Doe" DateOfBirth="1980-01-31">
    <department departmentID="100">
      <security>
        <AccessLevel>5</AccessLevel>
      </security>
    </department>
  </employee>
  <employee Name="Mary" Surname="Rose" DateOfBirth="1971-02-27">
    <department departmentID="102">
      <security>
        <AccessLevel>3</AccessLevel>
      </security>
    </department>
  </employee>
  <employee Name="Luke" Surname="Perry" DateOfBirth="1995-12-01">
    <department departmentID="104">
      <security>
        <AccessLevel>1</AccessLevel>
      </security>
    </department>
  </employee>
</company>