【问题标题】:Sql for xml: how to avoid a specific field is output as attribute?Sql for xml:如何避免将特定字段作为属性输出?
【发布时间】:2017-06-12 03:58:28
【问题描述】:

这个问题的出发点是Control on XML elements nesting using FOR XML

我希望输出改变

<security AccessLevel="5" />

<security>5<security/>

基本上不是将AccessLevel 显示为属性,我希望它的值成为元素security 的值。 如何达到这样的效果。 为了清楚起见,我在此处复制链接帖子中的示例:

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

select
  employee.Name,
  employee.Surname,
  employee.DateOfBirth,
  department.DepartmentID, 
  security.AccessLevel  -- THIS IS THE INVOLVED FIELD
from @Employees employee
join @Employees department on department.DepartmentID = employee.DepartmentID
join @Employees security on security.AccessLevel = employee.AccessLevel
for xml auto

【问题讨论】:

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


    【解决方案1】:

    我会在别名中使用@ 来生成xml 中的attributes。要获取accesslevel 作为元素,请不要将@ 添加到别名

    像这样的

    SELECT NAME         AS [@Name],
           Surname      AS [@Surname],
           DateOfBirth  AS [@DateOfBirth],
           DepartmentID AS [department/@DepartmentID],
           AccessLevel  AS [department/security]
    FROM   @Employees
    FOR xml path('employee') 
    

    结果:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      相关资源
      最近更新 更多