gpt4 book ai didi

mysql - 无法在 SQL 中使用 OPENXML 查询 XML 文件

转载 作者:行者123 更新时间:2023-11-30 22:06:34 24 4
gpt4 key购买 nike

我正在尝试使用 SQL Server 2014 查询大量 XML 文件。我正在使用以下代码,但我不确定语法有什么问题,因为没有返回任何内容。我怀疑 XML 文件有些奇怪。

如果只将部分 XML 文本直接放入查询文件而不是在本地指向它,那么它似乎可以工作,但我有很多文件,确实需要能够从本地源查询而无需手动操作的文件。

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

我的代码:

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

提前致谢。如果有更好的方法,请告诉我,我是在 SQL 中使用 XML 的新手。

最佳答案

有几个缺陷:

  • FROM OPENXML 已过时,不应再使用(存在极少数异常(exception))

  • 您的 XML 包含一个必须声明的默认命名空间

  • 你的 XPath 是错误的:/Return/ReturnData/IRS990ScheduleHIRS990ScheduleH/ 应该是 /Return/ReturnData/IRS990ScheduleH/

但无论如何,您应该求助于现代 XQuery 方法。像这样尝试:

--这会将 XML 读入声明的变量。

--注意您的 XML 是使用 utf-8 声明的,这可能会导致特殊字符出现问题...

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

--这是查询,首先声明命名空间,然后使用 .nodes().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)

关于mysql - 无法在 SQL 中使用 OPENXML 查询 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com