2012-04-29 13 views
1

以下のように属性を追加する方法はありますか?FOR XML PATH文に余分な属性を追加する方法

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

...前

後:私はこれを試してみましたが、何のデータは、要素のために返されないスタック上の検索に基づいて

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

<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, 
    '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)(そのページの "リテラル"の最初のインスタンスを検索します)。カラムエイリアスに区切り文字が必要な場合は、 ''二重引用符 ''または '[角括弧]'を使用する必要があります。 –

+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

関連する問題