2013-02-14 94 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>