2017-01-26 73 views
0

我舉例說明了我的問題。事實上,我在很多方面嘗試後都會想到解決方案,但我想問一下這個解決方案是否合適,或者是否因爲某種原因,最好使用其他方法。事實上,我需要控制如何創建元素。使用FOR XML對XML元素嵌套進行控制

我首先提出了一個視圖,其中包含我需要的所有數據,然後通過多次加入視圖從視圖中選擇。

我轉載的「複雜性」在這裏使用的,而不是一個視圖中的局部變量:

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) 

這是期望的結果(員工,部門和安全性是differeent元素 - 我的問題是要創造員工部門,安全就像在本實施例中):

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

正如我說我發現,在加入視圖(這裏表變量)每xml元素一次是一種解決方案:

-- declare @Employees table as above and then: 
    select 
     employee.Name, 
     employee.Surname, 
     employee.DateOfBirth, 
     department.DepartmentID, 
     security.AccessLevel from @Employees employee 
    join @Employees department on department.DepartmentID = employee.DepartmentID 
    join @Employees security on security.AccessLevel = employee.AccessLevel 
    for xml auto 

這會產生所需的輸出。

是否有多個連接的技術有for xml auto有效與否?

+0

如果它產生期望的結果,爲什麼不是很有效嗎? –

+0

我知道,但有時候有不推薦的功能或更好的做法,事實上,接受的答案顯示了一個更好的解決方案,它不使用連接+控制元素vs屬性 – LaBracca

回答

3

在別名中使用@xml中生成attributes。更簡單的方式來做到這一點

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

結果:

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

非常感謝。這給了我完全控制,也回答了我問的相關問題http://stackoverflow.com/questions/41877549/sql-for-xml-how-to-avoid-a-specific-field-is-output-as-attribute – LaBracca