How do I search for special characters (e.g. %) in SQL Server?

http://sqlserver2000.databases.aspfaq.com/how-do-i-search-for-special-characters-e-g-in-sql-server.html

There are several characters that have special meaning within a SQL query, for example the percent sign (%) in a LIKE query is a wildcard that essentially means "any number of characters can go here." Likewise, the underscore (_) is a wildcard that says "any single character can go here." So what if you are actually looking for a value that contains a literal percent sign? You will end up with bizarre results if you try the following: 
 
SELECT columns FROM table WHERE 
    column LIKE '%%%'
 
Instead, you can try one of the following solutions: 
 
SELECT columns FROM table WHERE 
    column LIKE '%[%]%' 
 
-- or 
 
SELECT columns FROM table WHERE 
    column LIKE '%/%%' ESCAPE '/'
 
The first query 'delimits' the special character with square brackets, telling the engine to treat it as a normal literal character instead of a character with special meaning. The second query uses a custom escape character -- you can use any character you like, just be careful that you aren't also expecting to use it as part of the literal string. 
 
Now, you might be wondering, how do I escape a square bracket? If you have something like this: 
 
SELECT columns FROM table WHERE 
    column LIKE '%[SQL Server Driver]%'
 
The results won't be what you expect, because an opening square bracket is considered a special character. Surprisingly, you can avoid this problem in much the same way, by one of the following two queries: 
 
SELECT columns FROM table WHERE 
    column LIKE '%[[]SQL Server Driver]%' 
 
-- or 
 
SELECT columns FROM table WHERE 
    column LIKE '%/[SQL Server Driver]%' ESCAPE '/'
 
You can do this replacement at the ASP side, before passing the string in, or within the SQL Server code itself.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值