2011-11-22 48 views
2

此代碼的問題是每個組中不總是有CEEBCode。它發現的第一個ceebcode實際上是在第二組中,並且與第一組中的其他元素相匹配。當存在不均勻元素時查詢XML

無論如何,當ceeb代碼不存在時,將這些組保持在一起?

select 
UIN, 
docXML.value(' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool/CEEBCode/text())[1]' 
    ,'varchar(6)' 
    ) as ceeb1, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool/IsGrad/text())[1]' 
    ,'varchar(5)' 
    ) as IsGradAns1, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool/Country/text())[1]' 
    ,'varchar(25)' 
    ) as Country1, 
docXML.value(' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool/CEEBCode/text())[2]' 
    ,'varchar(6)' 
    ) as ceeb2, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool/IsGrad/text())[2]' 
    ,'varchar(5)' 
    ) as IsGradAns2, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool/Country/text())[2]' 
    ,'varchar(25)' 
    ) as Country2 
from tblDocument 
where docxml is not null 

示例XML:

<SelfReportedTranscript> 
    <HighSchools> 
    <SelfReportedHighSchool> 
     <Name>Ramay Jr High School</Name> 
     <City>Fayetteville</City> 
     <Country>United States of America</Country> 
     <StateProvince>Arkansas</StateProvince> 
     <IsGrad>false</IsGrad> 
     <HighSchoolType>Domestic</HighSchoolType> 
    </SelfReportedHighSchool> 
    <SelfReportedHighSchool> 
     <Name>Fayetteville Sr High Sch</Name> 
     <CEEBCode>040770</CEEBCode> 
     <City>Fayetteville</City> 
     <Country>US</Country> 
     <StateProvince>AR</StateProvince> 
     <IsGrad>true</IsGrad> 
     <HighSchoolType>Domestic</HighSchoolType> 
    </SelfReportedHighSchool> 
    </HighSchools> 
</SelfReportedTranscript> 

這是SQL Server 2005 SP3

+0

您能否提供一份XML樣本? –

+0

我試過了。我不知道你是否可以看到我添加的所有內容。 – user1060395

+0

這適用於[1]情況,但[2]返回了空值。 – user1060395

回答

0

試試這個。 和[2]添加到SelfReportedHighSchool標記,因爲那是您從中獲取「行」的位置。還需要將最終的[2]更改爲[1]

select 
UIN, 
docXML.value(' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool[1]/CEEBCode/text())[1]' 
    ,'varchar(6)' 
    ) as ceeb1, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool[1]/IsGrad/text())[1]' 
    ,'varchar(5)' 
    ) as IsGradAns1, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool[1]/Country/text())[1]' 
    ,'varchar(25)' 
    ) as Country1, 
docXML.value(' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool[2]/CEEBCode/text())[1]' 
    ,'varchar(6)' 
    ) as ceeb2, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool[2]/IsGrad/text())[1]' 
    ,'varchar(5)' 
    ) as IsGradAns2, 
docxml.value 
    (' 
    (/SelfReportedTranscript/HighSchools/SelfReportedHighSchool[2]/Country/text())[1]' 
    ,'varchar(25)' 
    ) as Country2 
from tblDocument 
where docxml is not null 
+0

它的工作!謝謝!!!!!!!!!!!!!!!!!! – user1060395