检查XML是否只是一个特定的字符串?

时间:2017-10-30 16:44:05

标签: sql-server xml xquery

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

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)。

1 个答案:

答案 0 :(得分:2)

尝试

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