从XML导入到SQL的列名无效

时间:2016-06-15 14:31:31

标签: sql-server xml sql-server-2005 sqlxml

尝试将XML文件导入SQL时出错。代码如下所示:

USE MyDB

declare @xmldata as xml

set @xmldata = (SELECT CONVERT(XML, BulkColumn)AS Bulkcolumn
FROM OPENROWSET (BULK 'FILENAME', SINGLE_BLOB) as X)

INSERT INTO BenCalCopy1(BenefitCalcID, RangeBenID, CalculationID)
SELECT 

BenefitCalcID AS [BenefitCalcID],
RangeBenID AS [RangeBenID],
CalculationID AS [CalculationID]

给出的错误信息是:

Msg 207, Level 16, State 1, Line 11
Invalid column name 'BenefitCalcID'.
Msg 207, Level 16, State 1, Line 12
Invalid column name 'RangeBenID'.
Msg 207, Level 16, State 1, Line 13
Invalid column name 'CalculationID'.
Msg 207, Level 16, State 1, Line 8
Invalid column name 'BenefitCalcID'.

XML文件的名称为:

<row>
  <BenefitCalcID>'intvalue'</BenefitCalcID>
  <RangeBenID>'intvalue'</RangeBenID>
  <CalculationID>'intvalue'</CalculationID>
</row>

1 个答案:

答案 0 :(得分:0)

正如您所说,这些值是INT,我有&#39; INT&#39;在解析的xml列中。但是,如果值不是INT,您可以将其更改为&#39; VARCHAR(MAX)&#39;或者你需要什么。还要记住,xml节点(路径)区分大小写。例如&#39; / row&#39;不等于&#39; / Row&#39;。因此,如果您需要更新节点路径,请记住这一点。希望这对你有用。

DECLARE @XMLTable AS TABLE
(
    XMLData XML
)


DECLARE @XMLData AS XML

set @xmldata = (SELECT CONVERT(XML, BulkColumn)AS Bulkcolumn
FROM OPENROWSET (BULK 'FILENAME', SINGLE_BLOB) as X)


INSERT INTO @XMLTable
SELECT @XMLData

--SELECT * FROM @XMLTable

INSERT INTO BenCalCopy1(BenefitCalcID, RangeBenID, CalculationID)
SELECT 
     Data.value('(./BenefitCalcID)[1]','INT') BenefitCalcID
    ,Data.value('(./RangeBenID)[1]','INT') RangeBenID
    ,Data.value('(./CalculationID)[1]','INT') CalculationID
FROM
    @XMLTable X
    CROSS APPLY X.XMLData.nodes('/row') AS Tbl(Data)

编辑SQL Server 2005:

CREATE TABLE #XMLTable
(
    XMLData XML
)


DECLARE @XMLData AS XML

set @xmldata = (SELECT CONVERT(XML, BulkColumn)AS Bulkcolumn FROM OPENROWSET (BULK 'FILENAME', SINGLE_BLOB) as X)


INSERT INTO #XMLTable
SELECT @XMLData

--SELECT * FROM @XMLTable

INSERT INTO BenCalCopy1(BenefitCalcID, RangeBenID, CalculationID)
SELECT 
     Data.value('(./BenefitCalcID)[1]','INT') BenefitCalcID
    ,Data.value('(./RangeBenID)[1]','INT') RangeBenID
    ,Data.value('(./CalculationID)[1]','INT') CalculationID
FROM
    #XMLTable X
    CROSS APPLY X.XMLData.nodes('/row') AS Tbl(Data)