Sql for xml: how to avoid a specific field is output as attribute?

筅森魡賤 提交于 2019-12-10 12:18:31

问题


The stating point for this qusetion is Control on XML elements nesting using FOR XML

I would like that the output changes from

<security AccessLevel="5" />

to

<security>5<security/>

Basically instead of displaying AccessLevel as attribute I would like its value becomes the value of the element security. How to achieve such a result. I copy here the example from the linked post for clarity:

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

回答1:


I would do this using @ in alias name to generate the attributes in xml. To get the accesslevel as element just don't add @ to alias name

Something like this

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

Result:

<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>


来源:https://stackoverflow.com/questions/41877549/sql-for-xml-how-to-avoid-a-specific-field-is-output-as-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!