2013-05-31 87 views
1
<University> 
    <RegistrationCode>12859</RegistrationCode> 
    <Colleges> 
    <College> 
     <CollegeCode>0001</CollegeCode> 
     <CollegeName>NIMS</CollegeName> 
    </College> 
    <College> 
     <CollegeCode>0002</CollegeCode> 
     <CollegeName>OXFORD</CollegeName> 
    </College> 
    </Colleges> 
</University> 

我想使用SQL查詢從上面的XML中提取出來。有人可以幫助我嗎?使用SQL查詢讀取XML標記

RegistrationCode CollegeCode  CollegeName 
----------------------------------------------- 
12859    0001    NIMS 
12859    0002    OXFORD 
+0

可能的重複:http://stackoverflow.com/questions/15680259/parse-xml-in-sql-server – crush

回答

1

試試這個:

DECLARE @input XML = '<University> 
<RegistrationCode>12859</RegistrationCode> 
<Colleges> 
<College> 
<CollegeCode>0001</CollegeCode> 
<CollegeName>NIMS</CollegeName> 
</College> 
<College> 
<CollegeCode>0002</CollegeCode> 
<CollegeName>OXFORD</CollegeName> 
</College> 
</Colleges> 
</University>' 

SELECT 
    RegistrationCode = Univ.value('(RegistrationCode)[1]', 'int'), 
    CollegeCode = Colleges.value('(CollegeCode)[1]', 'int'), 
    CollegeName = Colleges.value('(CollegeName)[1]', 'varchar(100)') 
FROM 
    @input.nodes('University') AS XTbl(Univ) 
CROSS APPLY 
    Univ.nodes('Colleges/College') AS XTbl2(Colleges) 

這給了我所需的輸出。

基本上,你需要先有<University>節點(只是一個在這裏)的列表,以獲取註冊碼,然後從<University>節點你搶<Colleges>/<College>子節點使用CROSS APPLY和你搶那些學院的代碼和名稱子節點