Convert XML Nodes To Rows in SQL Server

不想你离开。 提交于 2019-12-20 02:58:25

问题


Consider the below sample:

declare @somexml as xml

set @somexml = '
<Settings>
    <Users>
        <ID>1</ID>
        <ID>2</ID>
        <ID>3</ID>
        <ID>4</ID>
        <ID>5</ID>
    </Users>
</Settings>'

The above XML has some ID values that I need to convert to rows of data that can be used in a temp table to perform joins against.

I can't quite get the syntax correct, I've tried a number of samples that I've come across:

SELECT T.r.value('.','int') as id
FROM @somexml.nodes('/Settings/Users') T(r)

Returns:

|ID    |
|------|
|12345 |

The following:

SELECT T.r.query('.') as id
from @somexml.nodes('/Settings/Users/ID') as T(r) 

Returns:

|ID         |
|-----------|
|<ID>1</ID> |
|<ID>2</ID> |
|<ID>3</ID> |
|<ID>4</ID> |
|<ID>5</ID> |

I'm getting close, but I want to remove the XML tags to just leave the ID values like so:

|ID |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |

Here's a fiddle if you want to play/solve that way: SQL Fiddle

Any help is appreciated as always.


回答1:


Replace T.r.query('.') as id with T.r.value('.', 'INT') as id




回答2:


SELECT T.r.value('.','int') as id
FROM @somexml.nodes('/Settings/Users/ID') T(r)


来源:https://stackoverflow.com/questions/22452413/convert-xml-nodes-to-rows-in-sql-server

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