[英]Group XML Column Data
Using SQL Server 2012. I have a table containing a group identifier and small snippets of XML. 使用SQL Server2012。我有一个包含组标识符和XML小片段的表。 Here is a sample:
这是一个示例:
CREATE TABLE temp (
GroupId [int] NOT NULL,
RawXml [xml] NULL
)
INSERT INTO temp VALUES (1, '<Item><Criteria Type="State" Values="CA"/><Criteria Type="State" Values="TX"/><Criteria Type="State" Values="FL"/></Item>')
INSERT INTO temp VALUES (1, '<Item><Criteria Type="Manager" Values="Tim"/></Item>')
INSERT INTO temp VALUES (2, '<Item><Criteria Type="Name" Values="Walters"/></Item>')
INSERT INTO temp VALUES (2, '<Item><Criteria Type="Manager" Values="Tim"/></Item>')
What I want to do is group the snippets of XML together by the GroupId to form a larger XML document so the end result is structured like this: 我想要做的是通过GroupId将XML的摘要分组在一起以形成一个更大的XML文档,因此最终结果的结构如下:
<Parent>
<Group GroupId="1">
<Item>
<Criteria Type="State" Values="CA"/>
<Criteria Type="State" Values="TX"/>
<Criteria Type="State" Values="FL"/>
</Item>
<Item>
<Criteria Type="Manager" Values="Tim"/>
</Item>
</Group>
<Group GroupId="2">
<Item>
<Criteria Type="Name" Values="Walters"/>
</Item>
<Item>
<Criteria Type="Manager" Values="Tim"/>
</Item>
</Group>
</Parent>
I fear the only solution is to concatenate the contents of the XML column first using some type of string concatenation method , and then using a FOR XML select statement, but I feel this will be too slow for my application. 我担心唯一的解决方案是先使用某种类型的字符串连接方法来连接XML列的内容,然后再使用FOR XML select语句来进行连接,但是我觉得这对于我的应用程序来说太慢了。 Am I missing something and there is an easy way to group xml data in this manner, or is string concatenation my only choice.
我是否缺少某些东西,并且有一种以这种方式对xml数据进行分组的简便方法,还是字符串串联是我的唯一选择。
Of course there is a simpler way: 当然,有一种更简单的方法:
declare @t table (
GroupId [int] NOT NULL,
RawXml [xml] NULL
);
INSERT INTO @t
VALUES (1, '<Item><Criteria Type="State" Values="CA"/><Criteria Type="State" Values="TX"/><Criteria Type="State" Values="FL"/></Item>'),
(1, '<Item><Criteria Type="Manager" Values="Tim"/></Item>'),
(2, '<Item><Criteria Type="Name" Values="Walters"/></Item>'),
(2, '<Item><Criteria Type="Manager" Values="Tim"/></Item>');
select sq.GroupId as [@GroupId],
(
select t.RawXml as [node()]
from @t t
where t.GroupId = sq.GroupId
for xml path(''), type
)
from (select distinct g.GroupId from @t g) sq
for xml path('Group'), type, root('Parent');
(I have replaced your original table with the equivalent TV because, well, I don't like to clean up databases of such tables afterwards. It doesn't introduce any difference with regards to the question.) (我已经用等效的电视替换了您的原始表,因为,好吧,我以后不希望清理此类表的数据库。这对问题没有任何区别。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.