I need to get table with Address
XML column from XML.
Here is what I do:
DECLARE @Person xml='<Person PersonID="a1fee068-aad4-459b-8ea7-063975f17bed">
<Address State="1" District="15" House="test" Additional="1" />
<Address State="8" District="11" Region="12" Neighborhood="13" Block="14" House="75" Additional="somewhere" />
</Person>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @Person
SELECT *
FROM
OPENXML(@handle, '/Person', 2)
WITH (
Address xml
)
EXEC sp_xml_removedocument @handle
The result is only first Address
from the XML. I can't understand why....
Any suggestions how get all records with Address
tag?
You can use a XML query like this:
DECLARE @Person xml=' <Person PersonID="a1fee068-aad4-459b-8ea7-063975f17bed"> <Address State="1" District="15" House="test" Additional="1" /> <Address State="8" District="11" Region="12" Neighborhood="13" Block="14" House="75" Additional="somewhere" /> </Person>' SELECT data.value('./@State', 'int') as State, data.value('./@District', 'int') as District, data.value('./@House', 'nvarchar(50)') as House, data.value('./@Additional', 'nvarchar(50)') as Additional, data.value('./@Region', 'int') as Region, data.value('./@Neighborhood', 'int') as Neighborhood, data.value('./@Block', 'int') as Block FROM @Person.nodes('/Person/Address') AS t1(data);
\nState | District | House | Additional | Region | Neighborhood | Block \n----: | -------: | :---- | :--------- | -----: | -----------: | ----: \n 1 | 15 | test | 1 | null | null | null \n 8 | 11 | 75 | somewhere | 12 | 13 | 14 \n\n
If you want each Address block:
\n SELECT data.query('.') \n FROM @Person.nodes('/Person/Address') AS t1(data) \n GO \n\n| (No column name) | \n| :------------------------------------------------------------------------------------------------------------- | \n| <Address State="1" District="15" House="test" Additional="1" /> | \n| <Address State="8" District="11" Region="12" Neighborhood="13" Block="14" House="75" Additional="somewhere" /> | \n
dbfiddle here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.