I am looking for something that works in SQL Server similar to the @
symbol in c# which causes a string to be taken as it\'s literal. Eg:
strin
I'd sanitize the string in the front-end application rather than try and do hokey stuff in SQL to work around this.
To search for "%" as a literal not wildcard in a string, it needs escaped as [%].
Now, SQL Server only need 3 characters escaping: % _ [
So, create a scalar udf to wrap this:
REPLACE(REPLACE(REPLACE(@myString, '[', '[[]'), '_', '[_]'), '%', '[%]')
Because of the simplicity (aka: very limited) pattern matching in SQL, nothing more complex is needed...
From the docs:
Syntax
match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]
Use the ESCAPE
option like so:
SELECT [Name]
FROM [Test]
WHERE [Name] LIKE (REPLACE(@searchText, '%', '%%') + '%') ESCAPE '%'
In TSQL, you can wrap the % and _ characters in brackets like so [%] [_] this tells SQL to treat them as literals.
I have tested and verified this works in SQL Server 7.0, 2000, and 2005.
http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx
Each character to be treated literally should be enclosed in square brackets. A right bracket is taken literally directly so don't enclose that one.
If you parameterize your query you don't need to worry about it.
UPDATE
As recursive stated in the comments, % still needs to be escaped even in parameterized queries, I didn't realize linq to sql was doing it automagically when I tested.
You can use ESCAPE 'x' where x is the character you wish to be the escape character. Linq to SQL does it like this
WHERE [Name] LIKE @searchText ESCAPE '~'
where @searchText = [some text with a~% character%]
or as others have stated it can be escaped with [%]
view the documentation