使用OPEN XML从数据存储中提取信息

问题描述 投票:0回答:1

我在数据库字段中保存了以下XML样本。

<datastore multipleDataSeparator=",">
  <group name="BasicDetails">
     <field name="CalculationType">REFUND</field>
  </group>
</datastore>

我想提取以下的值 CalculationType 节点,使用以下SQL脚本。

DECLARE @xml xml
DECLARE @idoc int
declare @lstrCalculationType varchar(50)
SET @xml = (
    '<datastore multipleDataSeparator=",">
  <group name="BasicDetails">
     <field name="CalculationType">REFUND</field>
  </group>
</datastore>'
            )


select @xml

EXEC sp_xml_preparedocument @idoc OUTPUT, @xml --Preparing XML handle

select @idoc,@xml 


SELECT 
@lstrCalculationType = CalculationType
FROM OPENXML(@idoc, 'datastore') --Row Pattern
WITH (
 CalculationType VARCHAR(50) 'BasicDetails/CalculationType'
)

select @lstrCalculationType

EXEC sp_xml_removedocument @idoc --Releasing memory

然而,输出为空 @lstrCalculationType. 任何指导或投入都将被感激。

sql-server xml datastore
1个回答
0
投票

我会使用内置的XQuery支持来做这件事。

DECLARE @xml xml

SET @xml = ('<datastore multipleDataSeparator=",">
                 <group name="BasicDetails">
                     <field name="CalculationType">REFUND</field>
                 </group>
             </datastore>')

SELECT 
    @xml.value('(/datastore/group/field[@name="CalculationType"]/text())[1]', 'varchar(25)')
© www.soinside.com 2019 - 2024. All rights reserved.