2012-04-29 65 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

相关问题