Search code examples
sql-serversql-server-2008-r2for-xml

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


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

Solution

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