2013-10-02 125 views
3

我試圖將一些XML導入到SQL中,但它不工作。這是我使用的SQL:將XML導入到SQL中

INSERT INTO learnertest (LearnRefNumber, FamilyName,GivenNames) 
SELECT learner.query('LearnRefNumber').value('.', 'VARCHAR(15)'), 
     learner.query('FamilyName').value('.', 'VARCHAR(30)'), 
     learner.query('GivenNames').value('.', 'VARCHAR(30)') 
FROM ( 
SELECT CAST(x AS XML) 
FROM OPENROWSET(
    BULK 'D:\xmltest.xml', 
    SINGLE_BLOB) AS T(x) 
    ) AS T(x) 
CROSS APPLY x.nodes('Message/Learner') AS X(learner); 

這裏是XML

<?xml version="1.0" encoding="utf-8" ?> 
<Message xsi:schemaLocation="http://www.theia.org.uk/ILR/2011-12/1 ILR-2012-13-Structure.xsd" xmlns="http://www.theia.org.uk/ILR/2012-13/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Header> 
     <CollectionDetails> 
      <Collection>ILR</Collection> 
      <Year>1213</Year> 
      <FilePreparationDate>2013-09-30</FilePreparationDate> 
     </CollectionDetails> 
     <Source> 
      <ProtectiveMarking>PROTECT-PRIVATE</ProtectiveMarking> 
      <UKPRN>10000000</UKPRN> 
      <TransmissionType>A</TransmissionType> 
      <SoftwareSupplier>xxx Ltd</SoftwareSupplier> 
      <SoftwarePackage>xx</SoftwarePackage> 
      <Release>7.12</Release> 
      <SerialNo>1</SerialNo> 
      <DateTime>2013-09-30T09:41:24</DateTime> 
     </Source> 
    </Header> 
    <LearningProvider> 
     <UKPRN>10004840</UKPRN> 
    </LearningProvider> 
    <Learner> 
     <LearnRefNumber>3333333</LearnRefNumber> 
     <ULN>44444444</ULN> 
     <FamilyName>Jones</FamilyName> 
     <GivenNames>Jane</GivenNames> 
     <DateOfBirth>1993-11-12</DateOfBirth> 
     <Ethnicity>31</Ethnicity> 
     <Sex>F</Sex> 
     <LLDDHealthProb>1</LLDDHealthProb> 
     <Domicile>XF</Domicile> 
     <PriorAttain>1</PriorAttain> 
     <ALSCost>0</ALSCost> 
     <Dest>97</Dest> 
    </Learner> 
</Message> 

查詢運行沒有錯誤,它只是不插入任何行。任何人都可以解釋我做錯了什麼?

+0

有點困惑,我對XML很陌生。你是否建議我應該編輯自己的XML? – Marshall10001

回答

1

因爲您的Message元素位於namespace中,所以您的xpaths也需要位於該名稱空間中,或者您需要tell SQL to assume a default namespace。後者是在這種簡單情況下更容易的選項:

;WITH XMLNAMESPACES(DEFAULT 'http://www.theia.org.uk/ILR/2012-13/1') 
INSERT INTO learnertest (LearnRefNumber, FamilyName,GivenNames) 
SELECT learner.query('LearnRefNumber').value('.', 'VARCHAR(15)'), 
     learner.query('FamilyName').value('.', 'VARCHAR(30)'), 
     learner.query('GivenNames').value('.', 'VARCHAR(30)') 
FROM ( 
SELECT CAST(x AS XML) 
FROM OPENROWSET(
    BULK 'D:\xmltest.xml', 
    SINGLE_BLOB) AS T(x) 
    ) AS T(x) 
CROSS APPLY x.nodes('Message/Learner') AS X(learner); 

只需添加第一行應該做的伎倆。

+0

非常感謝!這就是訣竅! – Marshall10001