【问题标题】:How to add extra atrributes in a FOR XML PATH statement如何在 FOR XML PATH 语句中添加额外的属性
【发布时间】:2012-04-29 15:29:10
【问题描述】:

有没有办法添加如下附加属性?

之前...

  <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>

感谢您的帮助。

布赖恩

【问题讨论】:

  • 顺便说一句,我建议不要使用'single quotes' 来分隔列别名; this syntax has been deprecated(在该页面上搜索“literal”的第一个实例)。当列别名需要分隔符时,您应该使用"double quotes",或者最好使用[square brackets]
  • 感谢 Aaron 的提示 Aaron。

标签: sql-server-2005 attributes for-xml-path


【解决方案1】:

你已经接近了 - 但如果你想要这个元素,你也必须在那里有那条线!

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多