简体   繁体   English

在SQL Server 2008 R2中查询XML数据

[英]Query XML data in SQL Server 2008 R2

I am trying to parse through an XML in SQL Server 2008 R2 and I am having some issues. 我试图通过SQL Server 2008 R2中的XML进行解析,但是遇到了一些问题。 I am trying to parse through the items for each parent node, but I'm not getting the solution The XML data is below: 我试图解析每个父节点的项目,但没有得到解决方案XML数据如下:

<MerchantInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Active>true</Active>
  <CreatedDate>2015-04-16T00:00:00+05:30</CreatedDate>
  <CreatedBy>63747</CreatedBy>
  <ModifiedBy>63747</ModifiedBy>
  <ModifiedUserName>charucsrawat@hpcl</ModifiedUserName>
  <MerchantCode>0</MerchantCode>
  <RetailOutletName>Gayatri Automobiles</RetailOutletName>
  <DealerName>Vandana Singh</DealerName>
  <ERPCode>16622710</ERPCode>
  <OwnerID>0</OwnerID>
  <ICICIAcDetailsRequired>false</ICICIAcDetailsRequired>
  <SupplyLocationCode>Mirzapur</SupplyLocationCode>
  <IsLive>false</IsLive>
  <LiveSAM>1</LiveSAM>
  <TestSAM>0</TestSAM>
  <OutletCategory>8001</OutletCategory>
  <HighwayNo>NH7</HighwayNo>
  <HighwayName>Mirzapur Rewa Road</HighwayName>
  <SecurityDeposit>10000</SecurityDeposit>
  <HSDSaleMonthly>200</HSDSaleMonthly>
  <Comments />
  <VerifiedDate>0001-01-01T00:00:00</VerifiedDate>
  <VerifiedBy>0</VerifiedBy>
  <isCloned>false</isCloned>
  <VerifiedByUserName />
  <ApprovedDate>0001-01-01T00:00:00</ApprovedDate>
  <ApprovedBy>0</ApprovedBy>
</MerchantInfo>

my code is : 我的代码是:

;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"' AS mi)
SELECT 
    T.C.value('mi:erpcode[1]','numeric') as erpcode,
    T.C.value('mi:SecurityDeposit[1]','varchar(50)') AS securitydeposit
FROM ChangeEvent ce
    CROSS APPLY changeddata.nodes('mi/erpcode[1]') AS T(C)
WHERE Ce.EntityTypeId = 2
    AND CAST(Ce.ChangedData AS VARCHAR(MAX)) LIKE '%16622710%'
GO

What I am looking for is: 我正在寻找的是:

erpcode  securitydeposit
16622710  10000

Kindly help 请帮助

You don't need ;WITH XMLNAMESPACES for this purpose since XML elements involved in the query doesn't use any namespace prefix and the XML document doesn't have defult namespace too. 您不需要;WITH XMLNAMESPACES来实现此目的,因为查询中涉及的XML元素不使用任何名称空间前缀,并且XML文档也没有defult名称空间。

Also note that XML element/attribute name are case-sensitive (fe erpcode != ERPCode ) : 另请注意,XML元素/属性名称区分大小写(fe erpcode != ERPCode ):

SELECT 
    T.C.value('ERPCode[1]','numeric') as erpcode,
    T.C.value('SecurityDeposit[1]','varchar(50)') AS securitydeposit
FROM ChangeEvent ce
    CROSS APPLY ChangedData.nodes('MerchantInfo') AS T(C)
WHERE Ce.EntityTypeId = 2
    AND T.C.value('ERPCode[1]','numeric') = 16622710

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM