如何在sql server中间使用通配符,如查询

时间:2016-01-18 01:18:38

标签: sql sql-server sql-like

在SQL Server中进行选择时,我可以在查询文本的开头或结尾添加%以表示我想要其他文本的任意数量的字符,但我不知道如何在中间执行此操作。

e.g。我想要SQL如下,

select *
From Table
Where name like '%[Error] Something failed in (%) session%'

当遇到以下数据时

Row | Date      | Log Message
1   |2016-01-01 |'[Error] Something failed in (Freds) session'
2   |2016-01-01 |'[Error] Something failed in (Ilenes) session'
3   |2016-01-01 |'[Error] Something failed in (Freds) session'; Some other warning
4   |2016-01-01 |'[Warning] Something else went wrong'
5   |2016-01-01 |'[Warning] Some other warning'

会给我

Row |Date       | Log Message
1   |2016-01-01 |'[Error] Something failed in (Freds) session'
2   |2016-01-01 |'[Error] Something failed in (Ilenes) session'
3   |2016-01-01 |'[Error] Something failed in (Freds) session'; Some other warning

但相反,它什么都没有回来,我需要改变什么。

1 个答案:

答案 0 :(得分:5)

问题是由于字符串中存在[][]LIKE运算符一起用于查找

  

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

所以你需要ESCAPE 方括号

select 1 
where '[Error] Something failed in (Freds) session'
like '%\[Error] Something failed in (%) session%' escape '\'

select 1 
where '[Error] Something failed in (Freds) session'
like '%[[]Error] Something failed in (%) session%'