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

发布于 2024-08-11 02:25:12 字数 521 浏览 2 评论 0原文

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

该表看起来像这样

| id | xml |

,XML 类似于

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

我想要获取 @name 属性与值匹配的所有 id。

我已经能够执行以下操作:

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

但是速度非常慢。

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

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.

The table looks something like this

| id | xml |

And the XML something similar to

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感性 2024-08-18 02:25:12

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

我的查询将是

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文