SQL Server转义下划线

SQL Server转义下划线

SQL Server Escape an Underscore

如何转义下划线字符?

我正在编写类似以下where子句的内容,并希望能够在末尾找到_d的实际条目。

1
Where Username Like '%_d'

适用于SQL Server 2000的LIKE的T-SQL参考:

You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The table shows several examples of using the LIKE keyword and the [ ] wildcard characters.

对于您的情况:

1
... LIKE '%[_]d'

显然@Lasse解决方案是正确的,但是还有另一种解决问题的方法:T-SQL运算符LIKE定义了可选的ESCAPE子句,该子句使您可以声明一个字符,该字符将下一个字符转义到模式中。

对于您的情况,以下WHERE子句是等效的:

1
2
3
WHERE username LIKE '%[_]d';            -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';


这对我有用,只是使用转义
'%\_%'


这些解决方案完全有意义。 不幸的是,没有一个对我有用。 我没有尝试麻烦,而是进行了以下工作:

1
2
3
select * from information_schema.columns
where replace(table_name,'_','!') not like '%!%'
order by table_name

这些都不适合我在SSIS v18.0中使用,因此我会做这样的事情:

WHERE CHARINDEX('_', thingyoursearching) < 1

..在那里我试图忽略带有下划线的字符串。 如果要查找带有下划线的内容,只需翻转一下即可:

WHERE CHARINDEX('_', thingyoursearching) > 0


推荐阅读