What characters should I exclude when searching oracle database? - sql

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("_","/_") +"%")

Related

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 '|'

How can I perform a SQL SELECT with a LIKE condition for a string containing an open bracket character?

I have a simple search query:
<cfquery name="_qSearch" dbtype="Query">
SELECT
*
FROM MyQoQ
WHERE
DESCRIPTION LIKE '%#URL.searchString#%'
</cfquery>
This query works excellently for most values. However, if someone searches for a value like "xxx[en", it bombs with the error message The pattern of the LIKE conditional is malformed..
Is there any way around this, since the bracket has a special use in CFQUERY?
QoQ shares a feature of TSQL (MS SQL Server) whereby it's not just % and _ that are wildcards in LIKE - it also supports regex-style character classes, as in[a-z] for any lowercase letter.
To escape these values and match the literal equivalents, you can use a character class itself, i.e. [[] will match a literal [, and of course you probably also want to escape any % and _ in the user input - you can do all three like so:
'%#Url.SearchString.replaceAll('[\[%_]','[$0]')#%'
That is just a simple regex replace (using String.replaceAll) to match all instances of [ or % or _ and wrap each one in [..] - the $0 on the replacement side represents the matched text.

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.

SQL LIKE Command trouble searching for '

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 '\'

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 "%".