2017-01-26 93 views
0

的說明點此qusetion是Control on XML elements nesting using FOR XMLSql 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 

回答

3

我會別名做到這一點使用@生成attributesxml。爲了得到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> 
相關問題