2017-05-30 72 views
1

我需要從XML中獲取Address XML列的表。在SQL Server中從XML中獲取XML列

這裏是我做的:

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 

結果是隻有第一Address從XML。我不明白爲什麼......

任何建議如何獲得與Address標記的所有記錄?

回答

3

您可以使用這樣的XML查詢:

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); 
 
State | District | House | Additional | Region | Neighborhood | Block 
----: | -------: | :---- | :--------- | -----: | -----------: | ----: 
    1 |  15 | test | 1   | null |   null | null 
    8 |  11 | 75 | somewhere |  12 |   13 | 14 

如果希望每個地址塊:

 
    SELECT data.query('.') 
    FROM @Person.nodes('/Person/Address') AS t1(data) 
    GO 

| (No column name)                        | 
| :------------------------------------------------------------------------------------------------------------- | 
| <Address State="1" District="15" House="test" Additional="1" />            | 
| <Address State="8" District="11" Region="12" Neighborhood="13" Block="14" House="75" Additional="somewhere" /> | 

dbfiddle here

+0

Get table then make XML FROM table? –

+0

你是什麼意思? – McNets

+0

我需要XML列的結果表。所以最好的結果是:row1 ='

'; row2 ='
' –