我正在尝试在单个列中合并的数据之间添加分隔符,并且在尝试这样做时遇到很多麻烦。
我正在使用一个大型XML文件(8+ megs)并尝试将数据的各个部分组合成我的数据库的单个列。以下查询正在执行此操作(排序),但当前没有数据分离。
WITH XmlFile (Contents) AS (
SELECT CONVERT (XML, BulkColumn)
FROM OPENROWSET (BULK 'C:\test.xml', SINGLE_BLOB) AS XmlData
)
SELECT c.value('(name)[1]', 'varchar(max)') AS [Name],
c.value('(stuff)[1]', 'varchar(max)') AS [Stuff]
FROM XmlFile CROSS APPLY Contents.nodes ('(/root/item)') AS t(c)
test.xml文件:
<root>
<item>
<name>Something</name>
<stuff>
<note>Test 123</note>
<note>Another Test</note>
</stuff>
</item>
</root>
返回的内容:
这几乎是我想要的!两个音符节点已合并为一个列...但我无法弄清楚如何在值“测试123 ,另一个测试”之间添加分隔符
非常感谢任何帮助!
答案 0 :(得分:3)
你可以使用XQuery,如下所示:
select
c.value('(name)[1]', 'varchar(max)') as [Name],
nullif(
replace(
c.query('
for $i in stuff/note/text()
return concat($i, ",")
'
).value('.', 'nvarchar(max)') + ','
,',,','')
, ',')
from @data.nodes ('/root/item') as t(c)
<强> sql fiddle demo 强>
答案 1 :(得分:1)
一个解决方案:
/* testing setup */
declare @t xml = '<root>
<item>
<name>Something</name>
<stuff>
<note>Test 123</note>
<note>Another Test</note>
</stuff>
</item>
<item>
<name>Something else</name>
<stuff>
<note>Test 345</note>
<note>Another 678</note>
</stuff>
</item>
</root>';
declare @handle int
EXEC sp_xml_preparedocument @handle OUTPUT, @t
select
P.n.value('(name/text())[1]', 'varchar(50)') as name,
stuff ((
SELECT
', ' + D.n.value('(text())[1]', 'varchar(50)')
FROM @t.nodes('/root/item') AS O(n)
CROSS APPLY O.n.nodes('stuff/note') AS D(n)
Where P.n.value('(name/text())[1]', 'varchar(50)') = O.n.value('(name/text())[1]', 'varchar(50)')
for xml path('')), 1, 2, '') as stuff
FROM @t.nodes('/root/item') AS P(n)