SQL Server中的LIKE运算符无法按预期工作

时间:2015-10-01 13:32:26

标签: sql sql-server sql-server-2012

我有以下SQL查询:

select
    zz.teststring TEST_STRING
    ,case when zz.teststring like 'JA%' then 'true' else 'false' end [JA%]
    ,case when zz.teststring like 'J%' then 'true' else 'false' end [J%]
    ,case when zz.teststring like 'JAA%' then 'true' else 'false' end [JAA%]
from 
    (select 'jaa' teststring) zz

输出

TEST_STRING      JA%       J%       JAA%
jaa              false     true     true

大/小写没有区别。

如果有人能解释为什么JA%会返回false,我真的很感激。

1 个答案:

答案 0 :(得分:4)

您需要检查排序规则可能设置为区分大小写:

<强> Demo

select
zz.teststring TEST_STRING
,case when zz.teststring like 'JA%' then 'true' else 'false' end [JA%]
,case when zz.teststring like 'J%' then 'true' else 'false' end [J%]
,case when zz.teststring like 'JAA%' then 'true' else 'false' end [JAA%]
from (
    select 'jaa' teststring
) zz

对于Case Insensitive添加COLLATE Latin1_General_CI_AS

select
zz.teststring TEST_STRING
,case when zz.teststring like 'JA%'  COLLATE Latin1_General_CI_AS then 'true' else 'false' end [JA%]
,case when zz.teststring like 'J%' COLLATE Latin1_General_CI_AS then 'true' else 'false' end [J%]
,case when zz.teststring like 'JAA%' COLLATE Latin1_General_CI_AS then 'true' else 'false' end [JAA%]
from (
    select 'jaa' teststring
) zz

修改

但我想知道你是如何得到答案的false, true, true?:

<强> Demo2

select
zz.teststring TEST_STRING
,case when zz.teststring like 'JA%' then 'true' else 'false' end [JA%]
,case when zz.teststring like 'J%' then 'true' else 'false' end [J%]
,case when zz.teststring like 'JAA%' then 'true' else 'false' end [JAA%]
from (
    select 'jaa' COLLATE Latin1_General_CS_AS teststring
) zz

感谢jarlh神秘解决了:

COLLATE Danish_Norwegian_CI_AI

<强> Demo3

使用某些语言&#39; aa&#39;被视为一个角色。