Monday, January 9, 2012

T-SQL - Searching for Wildcard Characters as Literals with LIKE

If you work with T-SQL long enough you will run into wildcards.
LIKE (Transact-SQL)
Now, wildcards are great.  They allow you to find all sorts of things in SQL very easily, with minimal typing, and, work.  However, if you want to search against a wildcard, it takes a different approach.  This trick came to me via this post,
How do I search for special characters (e.g. %) in SQL Server?
In my case, I was running a search for a field that started with a pound sign, like this, #Report 114.  If I ran this query it returned no results,
SELECT *
FROM Reports
WHERE Name LIKE '#%'
However, if I wrap the character that would normally be interpreted as a wildcard in brackets, [], I can perform the search as if the pound sign is a literal, not a wildcard.  It would look like this,
SELECT *
FROM Reports
WHERE Name LIKE '[#]%'

0 comments:

Post a Comment