2013-02-14 92 views
0

我有一個存儲過程,爲我們的數據庫中的一堆實體生成xml;我沒有寫出來,而那個傢伙已經回家了,所以我被卡住了,需要幫助。混合元素和SQL的XML路徑

的XML它的產生看起來是這樣的:

<Updates> 
    <Update>....stuff....</Update> 
    <Update>....stuff....</Update> 
    <Update>....stuff....</Update> 
    <Update>....stuff....</Update> 
</Updates> 

我需要它看起來像這樣:

<Updates> 
    <CommentUpdate>....stuff....</CommentUpdate> 
    <AttachmentUpdate>....stuff....</AttachmentUpdate> 
    <CommentUpdate>....stuff....</CommentUpdate> 
    <OtherTypeOfUpdate>....stuff....</OtherTypeOfUpdate> 
</Updates> 

根據特定列的值。目前,生成此xml的存儲過程的一部分是:

(select 
    u.ID as '@ID', 
    u.CreatedDate as '@CreatedDate', 
    (select * 
    from dbo.fsn_GetUserRef(u.CreatedBy, 
      case when @RetDepth = 'COMPLETE' 
      THEN 'FULL' 
      ELSE '' END) CreatedBy 
    for xml auto, type), 
    u.Type as 'Type', 
    u.Text as 'Text', 
    u.DocumentId as 'DocumentId'  
    from fusion_Updates u 
    where u.atom_id=atom.ID 
    for xml path('Update'), root('Updates'), type), 

幫助?

回答

0

對問題Sql XML Path with different children的回答包含適合您的解決方案。

我不完全理解您指定的查詢返回的數據結構。因此,我會給你一個結構更簡單的例子,你應該能夠適應你的需求。

假設你有一個UpdateEvent表,與EventDateTimeUpdateEventKey,和UpdateType,下面的查詢會給你想要的東西。

請注意,該表使用兩次,在外部選擇在記錄節點中生成變量標籤名稱,並在子選擇中生成字段節點。此外,PATH('')用於省略記錄節點(因爲這已經在外部選擇中生成)。

CREATE TABLE UpdateEvent (
     UpdateEventKey INT, 
     EventDateTime DATETIME, 
     UpdateType VARCHAR(50) 
     ); 
INSERT INTO UpdateEvent (UpdateEventKey, EventDateTime, UpdateType) 
     VALUES (1, GETDATE(), 'Comment'); 
INSERT INTO UpdateEvent (UpdateEventKey, EventDateTime, UpdateType) 
     VALUES (2, GETDATE() + (1/1440.0), 'Attachment'); 
INSERT INTO UpdateEvent (UpdateEventKey, EventDateTime, UpdateType) 
     VALUES (3, GETDATE() + (2/1440.0), 'Comment'); 
INSERT INTO UpdateEvent (UpdateEventKey, EventDateTime, UpdateType) 
     VALUES (4, GETDATE() + (3/1440.0), 'OtherTypeOf'); 

SELECT CAST('<' + U1.UpdateType + 'Update>' 
     + (SELECT * FROM UpdateEvent AS U2 
        WHERE U2.UpdateEventKey = U1.UpdateEventKey FOR XML PATH('')) 
     + '</' + U1.UpdateType + 'Update>' AS XML) 
     FROM UpdateEvent AS U1 FOR XML PATH(''), ROOT('Updates'), TYPE; 

這將生成以下XML。

<Updates> 
    <CommentUpdate> 
     <UpdateEventKey>1</UpdateEventKey> 
     <EventDateTime>2013-02-14T20:32:41.803</EventDateTime> 
     <UpdateType>Comment</UpdateType> 
    </CommentUpdate> 
    <AttachmentUpdate> 
     <UpdateEventKey>2</UpdateEventKey> 
     <EventDateTime>2013-02-14T20:33:41.767</EventDateTime> 
     <UpdateType>Attachment</UpdateType> 
    </AttachmentUpdate> 
    <CommentUpdate> 
     <UpdateEventKey>3</UpdateEventKey> 
     <EventDateTime>2013-02-14T20:34:41.727</EventDateTime> 
     <UpdateType>Comment</UpdateType> 
    </CommentUpdate> 
    <OtherTypeOfUpdate> 
     <UpdateEventKey>4</UpdateEventKey> 
     <EventDateTime>2013-02-14T20:35:41.777</EventDateTime> 
     <UpdateType>OtherTypeOf</UpdateType> 
    </OtherTypeOfUpdate> 
</Updates>