无法从XML文件中将数据读入SQL Server 2005

时间:2013-02-08 15:18:46

标签: sql xml sql-server-2005

我正在尝试使用以下脚本从XML文件中读取数据并将其插入SQL Server 2005上名为TermsTree的表中。

INSERT INTO TermsTree (TermID,ParentID,Name)

SELECT X.TermsTree.query('TermID').value('.', 'INT'),
       X.TermsTree.query('ParentID').value('.', 'INT'),
       X.TermsTree.query('Name').value('.', 'VARCHAR(2000)')
FROM (

SELECT CAST(x AS XML)
FROM OPENROWSET(
    BULK 'C:\Users\MehtabM\Desktop\GetAllTermTree.xml',
    SINGLE_BLOB) AS T(x)
    ) AS T(x)
CROSS APPLY x.nodes('ArrayOfTerm_Child/Term_Child') AS X(TermsTree);

XML文件的示例是

<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfTerm_Child xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
    <Term_Child>
        <TermID>2021</TermID>
        <Name>A. Geographic locations</Name>
        <ParentID>0</ParentID>
    </Term_Child>
    <Term_Child>
        <TermID>3602</TermID>
        <Name>Oceania</Name>
        <ParentID>2021</ParentID>
    </Term_Child>
    <Term_Child>
        <TermID>3604</TermID>
        <Name>Australasia</Name>
        <ParentID>3602</ParentID>
    </Term_Child>
    </Term_Child>
</ArrayOfTerm_Child>

1 个答案:

答案 0 :(得分:0)

http://www.sqlfiddle.com/#!3/18f84/15

declare @xml xml 
select @xml='<?xml version="1.0" encoding="utf-8"?>
 <ArrayOfTerm_Child xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
   <Term_Child>
<TermID>2021</TermID>
<Name>A. Geographic locations</Name>
<ParentID>0</ParentID>
 </Term_Child>
<Term_Child>
<TermID>3602</TermID>
<Name>Oceania</Name>
<ParentID>2021</ParentID>
 </Term_Child>
 <Term_Child>
<TermID>3604</TermID>
<Name>Australasia</Name>
<ParentID>3602</ParentID>
 </Term_Child>
 </ArrayOfTerm_Child>'

;WITH XMLNAMESPACES(DEFAULT 'http://tempuri.org/')
SELECT X.TermsTree.query('TermID').value('.', 'INT'),
       X.TermsTree.query('ParentID').value('.', 'INT'),
       X.TermsTree.query('Name').value('.', 'VARCHAR(2000)')
FROM @xml.nodes('/ArrayOfTerm_Child/Term_Child') X(TermsTree)