SQL Server - 如何将一个多元素 XML 分解为插入表中的单元素 XML 值? [英] SQL Server -- how to shred one multielement XML to single-element XML values inserted into table?
问题描述
我正在与 @x.nodes('...')
作斗争,因为我是 XQuery 的新手.我确实按照以下方式构造了 XML 变量 @x
:
I am fighting with @x.nodes('...')
as I am new to XQuery. I do have the XML variable @x
constructed the following way:
CREATE TABLE tab (a int, b int, c int);
GO
INSERT INTO tab (a, b, c) VALUES (1, 11, 111);
INSERT INTO tab (a, b, c) VALUES (2, 22, 222);
INSERT INTO tab (a, b, c) VALUES (3, 33, 333);
INSERT INTO tab (a, b, c) VALUES (4, 44, 444);
GO
DECLARE @x XML = (SELECT * FROM tab FOR XML RAW, TYPE);
当它的内容显示出来时,它看起来像:
When its content is displayed, it looks like:
<row a="1" b="11" c="111" />
<row a="2" b="22" c="222" />
<row a="3" b="33" c="333" />
<row a="4" b="44" c="444" />
即单个多行字符串.如何将单个多元素 XML 值分解到目标表中的多个单元素值?(我知道官方的 nodes() 方法(xml 数据类型) 文档页面,但我做错了.)
i.e. single multiline string. How can shred the single multielement XML value to many single-element value in the destination table? (I am aware of the official nodes() Method (xml Data Type) documentation page, but I am doing something wrong.)
CREATE TABLE tab2 (e XML);
??? ... @x.nodes('//row') ... ???
谢谢,彼得
附言该问题与 Service Broker 松散相关-如何从 XML 消息中提取行?
推荐答案
好的 - 所以你有一个包含你发布的 XML 的 XML 变量 - 你需要把它分解成单独的部分?
OK - so you have an XML variable that contains that XML you posted - and you need to shred this into its own individual bits?
尝试这样的事情:
SELECT
value_a = c.value('(@a)[1]', 'int'),
value_b = c.value('(@b)[1]', 'int'),
value_c = c.value('(@c)[1]', 'int')
FROM @x.nodes('/row') AS T(c)
这给了我一个输出:
这就是你要找的吗?
更新:好吧,如果我理解正确,这就是你想要的:
Update: ok, if I understand you correctly, this is what you want:
SELECT
c.query('.')
FROM @x.nodes('/row') AS T(c)
输出:
这篇关于SQL Server - 如何将一个多元素 XML 分解为插入表中的单元素 XML 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!