【问题标题】:Using normalize-string XPath function from SQL XML query?从 SQL XML 查询中使用 normalize-string XPath 函数?
【发布时间】:2010-04-13 12:10:08
【问题描述】:

是否可以使用 XPath“where”子句运行 SQL 查询,并在比较之前修剪尾随空格?

我有一个 SQL XML 列,其中的 XML 节点具有包含尾随空格的属性。我想找到一个给定的记录,它具有指定的属性值 - 没有尾随空格。

当我尝试时,我得到...

“没有函数'{http://www.w3.org/2004/07/xpath-functions}:normalize-space()'”

我尝试了以下方法(查询 1 有效,查询 2 无效)。这是在 SQL 2005 上。

declare @test table (data xml)
insert into @test values ('<thing xmlns="http://my.org.uk/Things" x="hello " />')

-- query 1
;with xmlnamespaces ('http://my.org.uk/Things' as ns0)
select * from @test where data.exist('ns0:thing[@x="hello "]') != 0

-- query 2
;with xmlnamespaces ('http://my.org.uk/Things' as ns0)
select * from @test where data.exist('ns0:thing[normalize-space(@x)="hello"]') != 0

感谢您的帮助。

【问题讨论】:

  • 您使用的是什么 SQL 数据库?甲骨文?微软 SQL? MySql?

标签: sql xpath where-clause


【解决方案1】:

SQL Server 也不包含允许正则表达式的replace() 函数。您最好使用contains(),它应该适用于您的搜索(不使用通配符时不会存在嵌套子字符串问题)。

select * from @test where data.exist('ns0:thing[contains(@x, "hello")]') != 0 

【讨论】:

    【解决方案2】:

    如果这是 SQL Server 2005/2008,SQLXML 4.0 不支持此函数 (normalize)。

    有关详细信息,请参阅this MSDN 文章。

    我建议将 XML 转换为字符串,并改用RTRIMLTRIM 和 SQL 的其他字符串函数。

    【讨论】:

    • 谢谢,奥德。事实证明,我的属性“x”的值始终是 6 个字符,因此我创建了一个 6 个字符的变量 (char(6)),并将该属性与“sql:variable”子句进行了比较。谢谢。
    猜你喜欢
    • 2017-03-06
    • 2022-01-04
    • 1970-01-01
    • 2019-12-14
    • 2010-12-22
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多