Where子句中的下划线会产生意外结果,为什么?

时间:2019-06-26 13:11:40

标签: sql-server tsql sql-server-2016 sql-like

我想查找所有以groupby开头的表,因此我编写了以下脚本:

TB_

令我惊讶的是,我得到了以下结果:

select *
from INFORMATION_SCHEMA.TABLES
where TABLE_NAME like 'TB_%'

我很好奇为什么?

2 个答案:

答案 0 :(得分:8)

表示任何单个字符与“ like”结合使用。参见

MSDN - LIKE (Transact-SQL)

  • %-零个或多个字符的任何字符串。
  • _-任何单个字符。 _a将与aaba等匹配。
  • [ ]-指定范围([a-f])或集合([abcdef])中的任何单个字符。
  • [^]-不在指定范围([^ a-f])或集合([^ abcdef])中的任何单个字符。

您可以使用[_]来匹配下划线,因此like 'TB[_]%'

或者您可以使用LIKE 'TB\_%' ESCAPE '\'.(感谢Jeroen Mostert)

答案 1 :(得分:4)

这是原因,因为您使用了下划线(_)符号。这意味着字符串允许您匹配单个字符。 选中此SQL LIKE Operator

最好使用WHERE COLUMN_NAME LIKE 'TB[_]%'WHERE COLUMN_NAME LIKE 'TB\_%'

%-百分号代表零个,一个或多个字符。

_-下划线表示单个字符。

[]-指定范围([a-f])或集合([abcdef])中的任何单个字符。

[^]-不在指定范围([^ a-f])或集合([^ abcdef])中的任何单个字符。

这里有一些例子

WHERE CustomerName LIKE 'a%'           Finds any values that start with "a"
WHERE CustomerName LIKE '%a'           Finds any values that end with "a"
WHERE CustomerName LIKE '%or%'         Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%'          Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%'          Finds any values that start with "a" and are at least 2 characters in length
WHERE CustomerName LIKE 'a%o'          Finds any values that start with "a" and ends with "o"
WHERE CustomerName LIKE '[a-e]arsen'   Finds any values that end with "arsen" and starting with any single character between "a" and "e"
WHERE CustomerName LIKE '[^a-e]arsen'  Finds any values that end with "arsen" and starting with any single character isn't between "a" and "e".