2015-01-01 64 views
3

我有一個看起來像這樣的XML數據:跨應用的不同層次

<game> 

    <teams> 
    <home id="363" color="000099">Brazil</home> 
    <away id="375" color="c5b358">Germany</away> 
    </teams> 

    <gameInfo> 
    <homeScore>1</homeScore> 
    <awayScore>7</awayScore> 
    <clock>90</clock> 
    </gameInfo> 

</game> 

我想創建具有順序列一個表:家,離開,homeID,awayID,homeScore,awayScore 。我似乎無法得到家庭ID(363和375)到表:

select * 
from (
select 

e.value('(./teams/home/text())[1]', 'nvarchar(100)') home, 
e.value('(./teams/away/text())[1]', 'nvarchar(100)') away, 
e.value('./teams/home/@id', 'int') homeID, 
e.value('./teams/away/@id', 'int') awayID 
e.value('(./gameInfo/homeScore/text())[1]', 'int') homeScore, 
e.value('(./gameInfo/awayScore/text())[1]', 'int') awayScore 

from (select * from [XMLTest].[dbo].[MATCHES]) t 
cross apply t.data.nodes('game') as t2(e) 

) events 

回答

2

你錯過提位置Id

value()總是需要一個positional參考來識別你想要的node

像這樣改變你的select

SELECT e.value('(./teams/home/text())[1]', 'nvarchar(100)') home, 
     e.value('(./teams/away/text())[1]', 'nvarchar(100)') away, 
     e.value('(./teams/home/@id)[1]', 'int')    homeID, 
     e.value('(./teams/away/@id)[1]', 'int')    awayID, 
     e.value('(./gameInfo/homeScore/text())[1]', 'int') homeScore, 
     e.value('(./gameInfo/awayScore/text())[1]', 'int') awayScore 
FROM [MATCHES] t 
     CROSS apply t.data.nodes('game') AS t2(e) 

例子:

DECLARE @xml XML='<game> 

    <teams> 
    <home id="363" color="000099">Brazil</home> 
    <away id="375" color="c5b358">Germany</away> 
    </teams> 

    <gameInfo> 
    <homeScore>1</homeScore> 
    <awayScore>7</awayScore> 
    <clock>90</clock> 
    </gameInfo> 

</game>' 

SELECT cs.e.value('(./teams/home)[1]', 'nvarchar(100)') home, 
     cs.e.value('(./teams/away)[1]', 'nvarchar(100)') away, 
     cs.e.value('(./teams/home/@id)[1]', 'int')   homeID, 
     cs.e.value('(./teams/away/@id)[1]', 'int')   awayID, 
     cs.e.value('(./gameInfo/homeScore)[1]', 'int') homeScore, 
     cs.e.value('(./gameInfo/awayScore)[1]', 'int') awayScore 
FROM @xml.nodes('game') AS cs (e) 

結果:

home away homeID awayID homeScore awayScore 
------ ------- ------ ------ --------- --------- 
Brazil Germany 363  375  1   7 
+1

比我正在建造更整潔 - 很好做。在風格上,或許全部或全部不包括* cs。*別名,而不是一半。 –

+1

@PieterGeerkens - 謝謝先生。剛剛更新 –