SQL LIKE Command trouble searching for ' - sql

Hi I am facing a problem with the like command in SQL,
I want to search for special characters within a column .
The special characters are a single quotation mark ' and { and }..
I have tried placing these special characters under [] but still it doesn't work for '
I have also used the except option but that was also of no help..
Waiting for a response soon

When you specify a value which has single quote, you need to double it.
SELECT *
FROM dbo.Northwind
WHERE Summary LIKE 'single''quotes%'

Try using this-
select * from <table> where <column> like '%''%'

SQL Server escaping is a pain because there are various ways to escape characters, each with different meaning and use case.
A single quote is escaped with another single quote: WHERE myfield LIKE '%''%'.

The general solution is to escape the special character like so:
SELECT .... WHERE my_column like '%\'%' ESCAPE '\'

Related

Like condition with multiple % in SQL Server

I want to search for the following string in a SP. How should I go about it?
cal.[dbo].[GetNumberOfWorkingDays]
I did not get expected results when I tried
'%cal.[dbo].[GetNumberOfWorkingDays]%'.
Does it work? : '%cal%GetNumberOfWorkingDays%'
Square bracket is reserved character in SQL Server like operator syntax, so you have to escape it:
like '%cal.\[dbo].\[GetNumberOfWorkingDays]%' escape '\'
See MSDN for details.
Another option would be to use CHARINDEX instead of LIKE. Since I am guessing this is in a where clause it would be something like this.
WHERE CHARINDEX('cal.[dbo].[GetNumberOfWorkingDays]', YourColumn, 0) > 0
https://msdn.microsoft.com/en-us/library/ms186323.aspx

How can I escape the wildcard for like operator? [duplicate]

This question also has the answer, but it mentions DB2 specifically.
How do I search for a string using LIKE that already has a percent % symbol in it? The LIKE operator uses % symbols to signify wildcards.
Use brackets. So to look for 75%
WHERE MyCol LIKE '%75[%]%'
This is simpler than ESCAPE and common to most RDBMSes.
You can use the ESCAPE keyword with LIKE. Simply prepend the desired character (e.g. '!') to each of the existing % signs in the string and then add ESCAPE '!' (or your character of choice) to the end of the query.
For example:
SELECT *
FROM prices
WHERE discount LIKE '%80!% off%'
ESCAPE '!'
This will make the database treat 80% as an actual part of the string to search for and not 80(wildcard).
MSDN Docs for LIKE
WHERE column_name LIKE '%save 50[%] off!%'
You can use the code below to find a specific value.
WHERE col1 LIKE '%[%]75%'
When you want a single digit number after the% sign, you can write the following code.
WHERE col2 LIKE '%[%]_'
In MySQL,
WHERE column_name LIKE '%|%%' ESCAPE '|'

What characters should I exclude when searching oracle database?

My SQL statement is like this
SELECT * FROM order WHERE clientname LIKE UPPER(?)
In Java code, I wrote
prepStatement.setObject(1,"%"+ userinput +"%")
I wonder how can I deal with special characters? Some characters, such as '%${}[],*', should they all be excluded or prevented from being used to search?
The LIKE operator interprets any % or _ characters as wildcards, so if you want to stop it interpreting characters input by the user, you need to use an escape character, e.g.:
SELECT * FROM order WHERE clientname LIKE UPPER(?) ESCAPE '/'
Then escape the user's input using something like (sorry, I'm not a Java guru so this might need some tweaking):
prepStatement.setObject(1,"%"+ userinput.ReplaceAll("%","/%").ReplaceAll("_","/_") +"%")

SQL Server LIKE containing bracket characters

I am using SQL Server 2008. I have a table with the following column:
sampleData (nvarchar(max))
The value for this column in some of these rows are lists formatted as follows:
["value1","value2","value3"]
I'm trying to write a simple query that will return all rows with lists formatted like this, by just detecting the opening bracket.
SELECT * from sampleTable where sampleData like '[%'
The above query doesn't work, because '[' is a special character. How can I escape the bracket so my query does what I want?
... like '[[]%'
You use [ ] to surround a special character (or range).
See the section "Using Wildcard Characters As Literals" in SQL Server LIKE
Note: You don't need to escape the closing bracket...
Aside from gbn's answer, the other method is to use the ESCAPE option:
SELECT * from sampleTable where sampleData like '\[%' ESCAPE '\'
See the documentation for details.
Just a further note here...
If you want to include the bracket (or other specials) within a set of characters, you only have the option of using ESCAPE (since you are already using the brackets to indicate the set).
Also you must specify the ESCAPE clause, since there is no default escape character (it isn't backslash by default as I first thought, coming from a C background).
E.g., if I want to pull out rows where a column contains anything outside of a set of 'acceptable' characters, for the sake of argument let's say alphanumerics... we might start with this:
SELECT * FROM MyTest WHERE MyCol LIKE '%[^a-zA-Z0-9]%'
So we are returning anything that has any character not in the list (due to the leading caret ^ character).
If we then want to add special characters in this set of acceptable characters, we cannot nest the brackets, so we must use an escape character, like this...
SELECT * FROM MyTest WHERE MyCol LIKE '%[^a-zA-Z0-9\[\]]%' ESCAPE '\'
Preceding the brackets (individually) with a backslash and indicating that we are using backslash for the escape character allows us to escape them within the functioning brackets indicating the set of characters.

How to escape a string for use with the LIKE operator in SQL Server?

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:
string text = "abcd\\efg";
Output of text = abcd\efg
string text = #"abcd\\efg";
Output of text = abcd\\efg
Note how the # affected the string to take every character as is.
Now I am not sure this is possible but here is my issue and maybe there is a better way to solve this. Consider the following basic query:
SELECT [Name]
FROM [Test]
WHERE [Name] LIKE (#searchText + '%')
My issue is if they put a %, _ or any other of those special characters that can affect my like clause. I want the match to act just like a 'starts with' function. So is there anything I can apply to the #searchText to say take this literally or is there possbibly a better solution that I am not thinking of?
Edit: I do not want the solution to be client side cleaning. I need this stored proc to work without relying on the data being passed in being cleaned.
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...
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
I'd sanitize the string in the front-end application rather than try and do hokey stuff in SQL to work around this.
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 '%'
If you don't want to modify the incoming text, you can use the "LEFT" function to create your own "STARTSWITH":
SELECT [Name]
FROM [Test]
WHERE #searchText = LEFT( [Name], LEN( #searchText ) )
(Note that you probably need to do extra work to handle the case of NULLs or empty string.)
EDIT: Removed the incorrect statement about using "LIKE" to search for "%".