【问题标题】:Check if XML is just a particular string?检查 XML 是否只是一个特定的字符串?
【发布时间】:2017-10-30 16:44:05
【问题描述】:

以下 SQL 为第二列和第三列的所有行返回 1。但是,它不应该只为第一行返回1s 吗?

with    t as ( select   cast('SomeText' as xml) x
               union all
               select   cast('<s>Test</s>' as xml)
             )
    select  * ,
            x.exist('contains(/text()[1], "SomeText.")') ,
            x.exist('/text() = "SomeText."')
    from    t
    where   x.exist('contains(/text()[1], "SomeText.")') = 1 
            and x.exist('/text() = "SomeText."') = 1;

我知道使用x.value('/', 'nvarchar(max)') = 'SomeText.' 可以解决问题。

问题是关于为什么 XQuery x.exist('/text() = "SomeText."') 或 x.exist('contains(/text()[1], "SomeText.")') 不工作(总是返回 true)。

【问题讨论】:

    标签: sql-server xml xquery


    【解决方案1】:

    试试

    with    t as (  select   cast('SomeText' as xml) x
                   union all
                   select   cast('SomeText.' as xml) x
                   union all
                   select   cast('<s>Test</s>' as xml)
                 )
        select  * ,
                x.query('contains(/text()[1], "SomeText.")') ,
                x.query('/text() = "SomeText."'),
                x.exist('.[contains(/text()[1], "SomeText.")]') ,
                x.exist('.[text()[1] eq "SomeText."]')
        from    t
    

    返回

    +-------------+------------------+------------------+------------------+------------------+
    |      x      | (No column name) | (No column name) | (No column name) | (No column name) |
    +-------------+------------------+------------------+------------------+------------------+
    | SomeText    | false            | false            |                0 |                0 |
    | SomeText.   | true             | true             |                1 |                1 |
    | <s>Test</s> | false            | false            |                0 |                0 |
    +-------------+------------------+------------------+------------------+------------------+
    

    我想您的原始代码正在返回这些行,因为 false 的结果仍然存在。

    declare @x xml;  
    set @x='';  
    select @x.exist('false()');  
    

    仍然返回1

    【讨论】:

      猜你喜欢
      • 2015-09-28
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 2015-03-18
      • 2017-12-16
      • 2011-08-03
      • 2019-05-11
      相关资源
      最近更新 更多