我有一个存储过程为我们数据库中的一堆实体生成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 :(得分:0)
问题Sql XML Path with different children的答案包含一个适合您的解决方案。
我不完全理解您指定的查询返回的数据的结构。因此,我将举例说明一个更简单的结构,你应该能够根据自己的需要进行调整。
假设您有一个UpdateEvent
表,其中包含UpdateEventKey
,EventDateTime
和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>