SQL Server — how to shred one multielement XML to single-element XML values inserted into table?

好久不见. 提交于 2019-12-02 03:39:30

问题


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" />

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') ... ???

Thanks, Petr

P.S. The question is loosely related to Service Broker -- how to extract the rows from the XML message?


回答1:


OK - so you have an XML variable that contains that XML you posted - and you need to shred this into its own individual bits?

Try something like this:

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)

That gives me an output of :

Is that what you're looking for?

Update: ok, if I understand you correctly, this is what you want:

SELECT
    c.query('.')
FROM @x.nodes('/row') AS T(c)

Output:



来源:https://stackoverflow.com/questions/11578904/sql-server-how-to-shred-one-multielement-xml-to-single-element-xml-values-ins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!