Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a string which contains an "&"

How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.

I'm not sure if it makes a difference, but I'm using Oracle 9i.

like image 527
Andrew Hampton Avatar asked Sep 30 '08 12:09

Andrew Hampton


People also ask

How do I add an apostrophe to a string in SQL?

The short answer is to use two single quotes - '' - in order for an SQL database to store the value as ' .

How do I add a quoted string in Oracle?

Answers. A string literal is enclosed in single quotes. If you want to embed a single quote within the literal (start, middle or end) just use two quotes instead of your single quote.


2 Answers

I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.

Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.

SET DEFINE OFF will stop sqlplus interpreting & this way.

But what if you need to use sqlplus variables and literal & characters?

  • You need SET DEFINE ON to make variables work
  • And SET ESCAPE ON to escape uses of &.

e.g.

set define on set escape on  define myvar=/forth  select 'back\\ \& &myvar' as swing from dual; 

Produces:

old   1: select 'back\\ \& &myvar' from dual new   1: select 'back\ & /forth' from dual  SWING -------------- back\ & /forth 

If you want to use a different escape character:

set define on set escape '#'  define myvar=/forth  select 'back\ #& &myvar' as swing from dual; 

When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:

set escape off set escape '#' 
like image 141
tardate Avatar answered Sep 22 '22 06:09

tardate


If you are doing it from SQLPLUS use

SET DEFINE OFF   

to stop it treading & as a special case

like image 36
hamishmcn Avatar answered Sep 24 '22 06:09

hamishmcn