使用XPath / XQuery在XML列上过滤SQL查询

时间:2022-12-10 07:53:22

I'm having a table with one XML column. I'd like to filter out the rows where a specific attribute in the XML match a string, essentially doing a WHERE or HAVING.

我有一个包含一个XML列的表。我想过滤掉XML中特定属性与字符串匹配的行,基本上是执行WHERE或HAVING。

The table looks something like this

该表看起来像这样

| id | xml |

And the XML something similar to

和XML类似的东西

<xml>
  <info name="Foo">
    <data .../>
  </info>
<xml>

I want to get all ids where the @name attribute matched a value.

我想得到@name属性与值匹配的所有ID。

I have been able to do the following:

我能够做到以下几点:

SELECT id, xml.query('data(/xml/info/@name)') as Value
FROM Table1
WHERE CAST(xml.query('data(/xml/info/@name)') as varchar(1024)) = @match

But it's incredibly slow.

但它非常缓慢。

There must be a better way of filtering on the output of the query.

必须有一种更好的方法来过滤查询的输出。

1 个解决方案

#1


20  

Found it. Instead of using query() I should be using exist().

找到了。我应该使用exists()而不是使用query()。

My query would then be

那我的查询就是

SELECT id, xml.query('data(/xml/info/@name)') as Value
FROM Table1
WHERE xml.exist('/xml/info/[@name=sql:variable("@match")]') = 1

#1


20  

Found it. Instead of using query() I should be using exist().

找到了。我应该使用exists()而不是使用query()。

My query would then be

那我的查询就是

SELECT id, xml.query('data(/xml/info/@name)') as Value
FROM Table1
WHERE xml.exist('/xml/info/[@name=sql:variable("@match")]') = 1