Tuesday, September 01, 2009

Underscores in SQL Server Query

Well, learn something new every day. I've been using SQL Server for close to 15 years but I guess I never needed to query for an underscore before today. An underscore is a special character in SQL server.

You can use the _ wildcard character to represent any single character in a query. For instance if you want to search for any four letter word that starts with w and ends with at you could search for:

where field="w_at"

In order to query for an underscore in SQL Server you need to escape it. The escape character in SQL Server is square bracket []. So if you want to find a particular column with an undercore in it you can query using the like statement as follows:

where field LIKE '%[_]%'

If you want to query for anything with two underscores in it then you'd have to escape each underscore like this:

where field LIKE '%[_][_]%'