【问题标题】:XML exist method not filtering records in SQL Server 2012XML 存在方法不过滤 SQL Server 2012 中的记录
【发布时间】:2020-02-10 18:06:30
【问题描述】:

我有两个问题:

  1. 我正在尝试在下面的示例中过滤属性@Type = "Bikes"。但我得到了所有 6 行。我应该只得到 3 行。为什么存在不在这里工作,我没有想法?

  2. 如何进一步过滤@Type = "Bikes" and Product = "Mountain"

我的代码如下:

declare @xml xml = '<StoreSurvey>
    <AnnualSales>800000</AnnualSales>
    <AnnualRevenue>80000</AnnualRevenue>
    <BankName>United Security</BankName>
    <BusinessType>BM</BusinessType>
    <YearOpened>1996</YearOpened>
    <Specialty>Mountain</Specialty>
    <SquareFeet>21000</SquareFeet>
    <Brands>2</Brands>
    <Internet>ISDN</Internet>
    <NumberEmployees>13</NumberEmployees>
    <Products Type="Bikes">
      <Product>Mountain</Product>
      <Product>Road</Product>
      <Product>Racing</Product>
    </Products>
    <Products Type="Clothes">
      <Product>Jerseys</Product>
      <Product>Jackets</Product>
      <Product>Shorts</Product>
    </Products>
  </StoreSurvey>'    

问题 1 的代码:

  select T.col.value('.','varchar(100)')  
  from @xml.nodes('/StoreSurvey/Products/Product') as T(col)
  where T.col.exist('/StoreSurvey/Products[@Type = "Bikes"]') =1

期望的输出:

Mountain
Road
Racing

问题 2 的代码:此代码导致“语法错误”:

  select T.col.value('.','varchar(100)')  
  from @xml.nodes('/StoreSurvey/Products/Product') as T(col)
  where T.col.exist('/StoreSurvey/Products[@Type = "Bikes"]/[Product = "Mountain"]') = 1

【问题讨论】:

    标签: sql-server xml-parsing


    【解决方案1】:

    这两个都返回您想要的第一个结果

      select T.col.value('.','varchar(100)')  
      from @xml.nodes('/StoreSurvey/Products/Product') as T(col)
      where T.col.exist('..[@Type = "Bikes"]') =1
    

    第二个似乎更自然,因为获取所有Product 节点然后备份并在父轴上应用过滤器(使用..)很奇怪

      select T.col.value('.','varchar(100)')  
      from @xml.nodes('/StoreSurvey/Products[@Type = "Bikes"]/Product') as T(col)
    

    目前尚不清楚您对 Q2 的确切期望结果是什么,但这会返回一个结果

    select T.col.value('.','varchar(100)')  
    from @xml.nodes('/StoreSurvey/Products[@Type = "Bikes"]/Product[text() = "Mountain"]') as T(col)
    

    【讨论】:

      【解决方案2】:

      对于这两种情况,请使用如下查询表单:

      with q as
      (
        select products.col.value('@Type','varchar(100)')  ProductType, 
               product.col.value('.','varchar(100)') Product
        from @xml.nodes('/StoreSurvey/Products') as products(col)
        cross apply products.col.nodes('Product') as product(col)
      )
      select * 
      from q
        where ProductType = 'Bikes'
          and Product = 'Mountain';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多