2016-06-14 63 views
1

我已將此樣本減少到絕對必要的最小值。所以,我知道,它沒有任何意義:-)如何使用SELECT FOR XML語句的AS中的列值

我知道,我可以從表下面的查詢選擇XML:

select id as [Direction/@Id], 
     direction as [Direction] 
from devicepdo 
for xml path('') 

結果將是這樣的:

<Direction Id="1">I</Direction> 
<Direction Id="2">O</Direction>`` 
<Direction Id="3">I</Direction> 
<Direction Id="4">O</Direction> 
.... 

列方向始終包含I或O,我想根據列值更改封閉的XML標記。

我的結果應該是這樣的:

<In Id="1">I</In> 
<Out Id="2">O</Out>`` 
<In Id="3">I</In> 
<Out Id="4">O</Out> 
.... 

所有我試圖在使用變量或科拉姆的「AS」子句失敗。

在我的查詢中,「方向」在「爲[方向/@ ID]」應根據列值是可變的。

這可能嗎?任何提示或想法?

回答

3

如果所有屬性均爲空,且內容爲空,則不會生成標籤。您可以使用這個事實根據每行中的值生成不同類型的標籤。

select 
    -- If direction is I then generate an In tag 
    case when direction = 'I' then id else null end as [In/@Id], 
    case when direction = 'I' then direction else null end as [In], 
    -- If direction is O then generate an Out tag 
    case when direction = 'O' then id else null end as [Out/@Id], 
    case when direction = 'O' then direction else null end as [Out] 
from devicepdo 
for xml path('') 

有效地你有所有可能的標籤的表達式,但其中一個類型的標籤是不希望的行,請使用case語句來使表達式零。

+0

你做了我的一天。非常感謝您的解決方案!我永遠不會自己發現這個! –