selecting individual xml node using SQL

守給你的承諾、 提交于 2019-12-03 02:14:19

You should use the query() Method if you want to get a part of your XML.

declare @XML xml

set @XML = 
'
<root>
  <row1>
    <value>1</value>
  </row1>
  <row2>
    <value>2</value>
  </row2>
</root>
'

select @XML.query('/root/row2')

Result:

<row2>
  <value>2</value>
</row2>

If you want the value from a specific node you should use value() Method.

select @XML.value('(/root/row2/value)[1]', 'int')

Result:

2

Update:

If you want to shred your XML to multiple rows you use nodes() Method.

To get values:

declare @XML xml

set @XML = 
'
<root>
  <row>
    <value>1</value>
  </row>
  <row>
    <value>2</value>
  </row>
</root>
'

select T.N.value('value[1]', 'int')
from @XML.nodes('/root/row') as T(N)

Result:

(No column name)
1
2

To get the entire XML:

select T.N.query('.')
from @XML.nodes('/root/row') as T(N)

Result:

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