在sql查询中,我们经常需要原样输出字符串,如果字符串中含有大量的单引号、双引号或者特殊字符,那么需要用单引号转义拼接字符串,这样会非常的麻烦。 oracle提供了一个Q-quote的表达式来原样输出字符串。
在SQL或者PLSQL中如果要表达一个带有特殊字符的字符串时,通常要用‘’包装起来。但如果字符串本身包含‘或者“这样的字符,那么实现起来有点繁琐。
比如:My Name is ‘Ma Yu Ping’
用SQL实现:
SQL> select ‘My Name Is ”Ma Yu Ping”’ names from dual;
NAMES
———————————————-
My Name Is ‘Ma Yu Ping’
SQL> select ‘My Name Is "Ma Yu Ping"’ names from dual;
NAMES
———————————————-
My Name Is "Ma Yu Ping"
在Oracle中,single-quote(‘)是一个表示字符串的关键字。所以在字符串中用两个”表示一个实际的单引号字符。所有才会有了上面第一条SQL的’My Name Is ”Ma Yu Ping”’ 。双引号“被识别为一个实际的的字符串,第二条sql中的双引号不用括引。其实Oracle提供了一个Q-quote的表达式,用来简化SQL或PLSQL中字符串的表示。
SQL> select q’[My Name Is "Ma Yu Ping"]‘ names from dual;
NAMES
———————————————-
My Name Is "Ma Yu Ping"
SQL> select q’[My Name Is 'Ma Yu Ping']‘ names from dual;
NAMES
———————————————-
My Name Is ‘Ma Yu Ping’
语法很简单,必须将要表示的字符串用一对特殊字符括起来,这对字符必须一致。
SQL> select q’[My Name Is 'Ma Yu Ping'|' names from dual;
ERROR:
ORA-01756: 引号内的字符串没有正确结束
SQL> select q'|My Name Is 'Ma Yu Ping'|' names from dual;
NAMES
----------------------------------------------
My Name Is 'Ma Yu Ping'
常用简化的写法,比如一个where c='d'的产量表达式的表示方法。
SQL> select 'where c=''d''' from dual; --老的写法
'WHEREC=''D'''
----------------------
where c='d'
SQL> select 'where c='d'' from dual; --原则的写法受’表达式的影响出错
select 'where c='d'' from dual
*
第 1 行出现错误:
ORA-00923: FROM keyword not found where expected
SQL> select q'[where c='d']‘ from dual; --使用q-quote表达式的写法
Q’[WHEREC='D']‘
———————-
where c=’d’
SELECT Q'[I'm a boy,my name is 'david']' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'(I'm a boy,my name is 'david')' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'{I'm a boy,my name is 'david'}' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'|I'm a boy,my name is 'david'|' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'aI'm a boy,my name is 'david'a' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'2I'm a boy,my name is 'david'2' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'@I 'm a boy,my name is 'david'@' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'*I'm a boy,my name is 'david'*' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'#I'm a boy,my name is 'david'#' FROM DUAL; --结果:I'm a boy,my name is 'david'
SELECT Q'[[@#$%^&*~?/" ']]' FROM DUAL; --结果:[@#$%^&*~?/" ']
oracle本身默认的是单引号,但是在大家写存储过程或者写SQL语句时,有时候需要拼SQL或者是SQL的值里需要传入含单引号的值,此时就需要使用两个单引号"''"来进行转义,其实oracle本身提供了这种转换默认单引号为其他标识的方法那就是——"q"
q [Oracle's quote operator]q'c text-to-be-quoted c' c is a single character (called the quote delimiter).
With the ?quote operator? apostrophes don't have to
be doubled:
SQL> select q'#Oracle's quote operator#' from dual;
Q'#ORACLE'SQUOTEOPERATO ----------------------- Oracle's quote operator