[xml存在的方法不过滤sql server 2012中的记录

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

我有2个问题:

Q1。我在下面的示例中尝试过滤属性@Type =“ Bikes”。但是我得到所有6行。我应该只得到3行。为什么不在这里工作,我不知道?

Q2。如何进一步过滤@Type =“ Bikes”和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个回答
0
投票

对于这两种方法,请使用如下查询表:

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

0
投票

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

  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)
© www.soinside.com 2019 - 2024. All rights reserved.