问题
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