我遇到在SQL Server列中有重复XML属性的情况。
DB fiddle for sql: http://sqlfiddle.com/#!18/bfd7d8
桌子:
create table test12
(
id int,
data xml
);
insert into test12 (id,data)
values (1,
'<test1>
<Attribute>FGHH</Attribute>
<Value>Long</Value>
</test1>
<test1>
<Attribute>FGHH</Attribute>
<Value>Long</Value>
</test1>'
)
有问题的 XML 是
'<test1>
<Attribute>FGHH</Attribute>
<Value>Long</Value>
</test1>
<test1>
<Attribute>FGHH</Attribute>
<Value>Long</Value>
</test1>'
任何人都可以就如何从 XML 中删除这些重复行之一提供一些建议。我只想保留 1 个重复的 XML。所以我正在寻找的输出是:
<test1>
<Attribute>FGHH</Attribute>
<Value>Long</Value>
</test1>'
我知道我可以使用 DISTINCT 来选择它,但我如何实际从 XML 中删除这种重复项?任何帮助都会很棒。谢谢
老实说:在表格集中读出这一点并从头开始重新创建 XML 可能会更容易。
但是XQuery也可以帮助你:
create table test12
(
id int,
data xml
);
--我添加了一些节点并更改了<Value>
以反映给定的节点
insert into test12 (id,data)
values (1,
'<test1>
<Attribute>FGHH</Attribute>
<Value>blah 1</Value>
</test1>
<test1>
<Attribute>OneMore</Attribute>
<Value>blah 1</Value>
</test1>
<test1>
<Attribute>FGHH</Attribute>
<Value>blah 2</Value>
</test1>
<test1>
<Attribute>SomeOther</Attribute>
<Value>blah 1</Value>
</test1>'
);
GO
--这是查询
SELECT t.id
,t.data.query('for $attrValue in distinct-values(/test1/Attribute/text())
return /test1[Attribute = $attrValue][1]')
FROM test12 t;
简而言之,这个想法:
XQuery
函数distinct-values()
将返回给定路径上所有值的不同列表。在这种情况下,我们得到一个text()
节点的列表。
现在我们可以遍历此列表并返回每个 <test1>
元素的第一个出现,其中 <Attribute>
等于列表变量。结果,我们得到了每种类型中的第一个:
<test1>
<Attribute>FGHH</Attribute>
<Value>blah 1</Value>
</test1>
<test1>
<Attribute>OneMore</Attribute>
<Value>blah 1</Value>
</test1>
<test1>
<Attribute>SomeOther</Attribute>
<Value>blah 1</Value>
</test1>