如何在FOR XML PATH语句中添加额外的属性

时间:2012-04-29 15:29:10

标签: sql-server-2005 attributes 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')

基于对Stack的搜索,我尝试了这个但没有返回该元素的数据。

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 个答案:

答案 0 :(得分: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