2017-03-16 156 views
1

有人可以解释我这个charindex函数在SQL中的奇怪行为吗?我们正在搜索第二个字母是'o'的值。我不明白为什么查询1和3不会返回'OO software ontwerp',而在查询4中使用类似的操作符时它会显示出来。即使当我在查询5中搜索大写字母'O'时,'OO software ontwerp'值也不显示。SQL Charindex与LIKE运算符

DECLARE @T TABLE (Titel VARCHAR(255)) 
INSERT INTO @T VALUES 
('Mobotu'),('OO software ontwerp'),('Compleet handboek Access 97'),('Compleet handboek Access 2000'),('Compleet handboek Access 95') 

查询1

SELECT titel FROM @T WHERE CHARINDEX('o', titel, 1) = 2 

    titel 
----------------------------- 
1 Mobotu 
2 Compleet handboek Access 97 
3 Compleet handboek Access 2000 
4 Compleet handboek Access 95 

查询2

SELECT titel FROM @T WHERE CHARINDEX('o', titel, 1) = 1 

    titel 
----------------------------- 
1 OO software ontwerp 

查询3

SELECT titel FROM @T WHERE CHARINDEX('o', LOWER(titel), 1) = 2 

    titel 
----------------------------- 
1 Mobotu 
2 Compleet handboek Access 97 
3 Compleet handboek Access 2000 
4 Compleet handboek Access 95 

查询4

SELECT titel FROM @T WHERE titel LIKE '_o%' 

    titel 
----------------------------- 
1 Mobotu 
2 OO software ontwerp 
3 Compleet handboek Access 97 
4 Compleet handboek Access 2000 
5 Compleet handboek Access 95 

查询5

SELECT titel FROM @T WHERE CHARINDEX('O', titel, 1) = 2 

    titel 
----------------------------- 
1 Mobotu 
2 Compleet handboek Access 97 
3 Compleet handboek Access 2000 
4 Compleet handboek Access 95 
+0

我发现它,charindex返回搜索到的字母的第一个位置。我必须设置WHIN CHARINDEX('o',titel,2)= 2。我的错误。 – Kevin

回答

2

charindex()找到的第一个发生,like一个模式匹配,patindex()也匹配的图案,但仍返回第一次出现。你可以使用patindex('_o%',titel)=1

select titel 
from @t 
where patindex('_o%', titel) = 1 

rextester演示:http://rextester.com/JCHFQT86136

回报

+-------------------------------+ 
|    titel    | 
+-------------------------------+ 
| Mobotu      | 
| OO software ontwerp   | 
| Compleet handboek Access 97 | 
| Compleet handboek Access 2000 | 
| Compleet handboek Access 95 | 
+-------------------------------+ 

select titel 
from @t 
where patindex('%e%', titel) = 6 

回报:

+-------------------------------+ 
|    titel    | 
+-------------------------------+ 
| Compleet handboek Access 97 | 
| Compleet handboek Access 2000 | 
| Compleet handboek Access 95 | 
+-------------------------------+