Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping special characters in SQL

Tags:

sql

oracle11g

Is there an easy way in Oracle to escape special characters in a SQL statement? (i.e. %, &, ') I saw this link in regard to manually escaping characters, but I thought Oracle may have provided an easier way to do so.

Note: I'm generating dynamic SQL select statements through an ORM.

like image 570
contactmatt Avatar asked Jan 06 '12 20:01

contactmatt


People also ask

How do I escape a string in SQL?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

What is the '\ n escape character?

Escape sequences are used inside strings, not just those for printf, to represent special characters. In particular, the \n escape sequence represents the newline character.


2 Answers

If using bind variables and ORM, embedded single quotes and ampersands should be handed automatically; those are special characters in SQL*Plus or SQL*Developer.

To use LIKE where looking for the literal characters % and _ (not their multi- and single-character wildcard versions), you'd use the escape clause of the like condition:

select * from my_table where some_text like '/%%' escape '/';

will only return the rows where some_text begins with a percent sign.

like image 57
Adam Musch Avatar answered Nov 08 '22 07:11

Adam Musch


It seems you're looking for something like the command SET DEFINE OFF, which you can run and it affects the whole SQL session. This command, however, only prevents Oracle from giving special meaning to the ampersand character. It doesn't affect other special characters such as the single quote.

A couple of links to additional information regarding escaping characters follow:

https://forums.oracle.com/forums/thread.jspa?threadID=2256637

http://docs.oracle.com/cd/B10501_01/text.920/a96518/cqspcl.htm

like image 39
Eduardo Avatar answered Nov 08 '22 05:11

Eduardo