SQL Charindex vs LIKE运算符

时间:2017-03-16 20:51:27

标签: sql sql-server tsql charindex

有人可以解释一下SQL中charindex函数的奇怪行为吗?我们正在搜索第二个字母为“o”的值。我不明白为什么查询1和3不返回'OO software ontwerp',而在查询4中使用like运算符它确实显示。即使我在查询5中搜索大写字母“O”,也不会显示“OO software ontwerp”值。

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

1 个答案:

答案 0 :(得分: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   |
+-------------------------------+