3

我正在尝试将一些 XML 导入 SQL,但它不起作用。这是我正在使用的 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>

查询运行没有错误,它只是不插入任何行。谁能解释我做错了什么?

4

1 回答 1

1

因为您的Message元素在命名空间中,所以您的 xpath 也需要在该命名空间中,或者您需要告诉 SQL 假定默认命名空间。在这种简单的情况下,后者是更简单的选择:

;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);

只需添加第一行就可以了。

于 2013-10-02T11:27:15.953 回答