XML 存在方法不过滤 SQL Server 2012 中的记录

XML exist method not filtering records in SQL Server 2012

我有两个问题:

  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 的代码:此代码导致 "syntax error":

  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

对于这两者,请使用如下查询表单:

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';

这两个 return 您想要的第一个结果

  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)

尚不清楚您对第二季度的确切期望结果是什么,但这是 return 的结果

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