2012-04-29 51 views
1

是否有方法添加如下的其他屬性?如何在FOR XML PATH語句中添加額外的屬性

之前...

<Event id="CE1127552523644210147"> 
    <Title>General Surgery Orange Rotation </Title> 
    <Duration>671</Duration> 
    <InstructionalMethod>Clinical Rotation</InstructionMethod> 
    </Event> 

後:

<Event id="CE1127552523644210147"> 
    <Title>General Surgery Orange Rotation </Title> 
    <Duration>671</Duration> 
    <InstructionalMethod Primary='True'>Clinical Rotation</InstructionMethod> 
    </Event> 

原始查詢:

select 
    id as '@id', 
    Title, 
    Duration, 
    InstructionalMethod 
from MyTable 
for XML PATH ('Event'), ROOT('Events') 

基於堆棧上搜索我曾嘗試這一點,但該元素沒有數據返回。

select 
    id as '@id', 
    Title, 
    Duration, 
    'True' AS 'InstructionalMethod/@Primary' 
from mytable 
for XML PATH ('Event'), ROOT('Events'), TYPE 

結果:

<Event id="CE1127552523644210147"> 
    <Title>General Surgery Orange Rotation </Title> 
    <Duration>671</Duration> 
    <InstructionalMethod Primary="True" /> 
    </Event> 

感謝您的幫助。

布賴恩

+1

順便說一句,我建議不要使用''單一quotes''分隔欄別名; [此語法已被棄用](http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx)(在該頁面上搜索「literal」的第一個實例)。當列別名需要分隔符時,應該使用''雙引號'',或者最好使用'[方括號]'。 –

+0

感謝亞倫爲你的提示亞倫。 – user1364303

回答

2

你接近 - 但如果你想要的元素,你必須有在那裏,線,太!

試試這個:

SELECT 
    id as '@id', 
    Title, 
    Duration, 
    'True' AS 'InstructionalMethod/@Primary', 
    InstructionalMethod -- add this line to get the actual value as element 
FROM 
    dbo.mytable 
FOR XML PATH ('Event'), ROOT('Events'), TYPE 
+0

非常感謝Marc_s :-) – user1364303

相關問題