Unable to Query XML file with OPENXML in SQL

我怕爱的太早我们不能终老 提交于 2019-12-24 07:59:26

问题


I am trying to query a good number of XML files using SQL Server 2014. I am using the below code and I am unsure what is wrong with the syntax because nothing is being returned. My suspicion is there is something strange with the XML file.

If put in only parts of the XML text directly into the query file instead of pointing to it locally then it seems to work but I have a lot of files and really need to be able to query from a local source without manual manipulation of the files.

Example XML: https://s3.amazonaws.com/irs-form-990/201600349349300510_public.xml

My code:

DECLARE @x xml
SELECT @x = R
FROM OPENROWSET (BULK 'C:\Users\USER\990\Example.xml', SINGLE_BLOB) AS     ReturnData(R)

SELECT @x

DECLARE @hdoc int

EXEC sp_xml_preparedocument @hdoc OUTPUT, @x

SELECT * FROM OPENXML (@hdoc, '/Return/ReturnData/IRS990ScheduleHIRS990ScheduleH/FinancialAssistanceAtCostTyp',3)  
  WITH (FinancialAssistancePolicyInd  int   '../FinancialAssistancePolicyInd',  
        FPGReferenceDiscountedCareInd int   '../FPGReferenceDiscountedCareInd',
        PersonsServedCnt int,
        NetCommunityBenefitExpnsAmt int)  

EXEC sp_xml_removedocument @hdoc

Thanks in advance. IF there is a better way to do this then please do let me know, I am new to working with XML in SQL.


回答1:


There are several flaws:

  • FROM OPENXML is outdated and should not be used any more (rare exceptions exist)

  • your XML included a default namespace, which must be declared

  • your XPath is wrong: /Return/ReturnData/IRS990ScheduleHIRS990ScheduleH/ should be /Return/ReturnData/IRS990ScheduleH/

But anyway you shoudl turn to modern XQuerymethods. Try it like this:

--This will read the XML into a declared variable.

--attention Your XML is declared with utf-8, this might lead to problems with special characters...

DECLARE @x xml
SELECT @x = R
FROM OPENROWSET (BULK 'C:\Users\USER\990\Example.xml', SINGLE_BLOB) AS ReturnData(R);

--This is the query, first declare the namespace(s), than use .nodes() and .value():

WITH XMLNAMESPACES(DEFAULT 'http://www.irs.gov/efile'
                          ,'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
SELECT ct.value('(FinancialAssistancePolicyInd)[1]','int') AS FinancialAssistancePolicyInd
      ,ct.value('(FPGReferenceDiscountedCareInd)[1]','int') AS FPGReferenceDiscountedCareInd
      ,ct.value('(FinancialAssistanceAtCostTyp/PersonsServedCnt)[1]','int') AS PersonsServedCnt
      ,ct.value('(FinancialAssistanceAtCostTyp/NetCommunityBenefitExpnsAmt)[1]','int') AS NetCommunityBenefitExpnsAmt
FROM @x.nodes('/Return/ReturnData/IRS990ScheduleH') AS A(ct)


来源:https://stackoverflow.com/questions/41510737/unable-to-query-xml-file-with-openxml-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!