自ORACLE10g开始,PL/SQL提供了一种自定义引用的语法。他可以使得我们在写动态SQL时,不用考虑外部的单引号而更改内部的引号规则。
简单的举例说明:
declare
v_sql varchar2(1000);
begin
--method 1
v_sql := 'select ''a'' from dual';
dbms_output.put_line(v_sql);
--method 2
v_sql := 'select '||'''a'''||' from dual';
dbms_output.put_line(v_sql);
--method 3
v_sql := q'[select 'a' from dual]';
dbms_output.put_line(v_sql);
end;
--output
select 'a' from dual
select 'a' from dual
select 'a' from dual
以上SQL得到的结果都相同。
我们知道动态SQL通常写在变量的引号内,作为一个字符串。如果这个SQL本身也带有单引号,在不使用自定义引用规则时,我们通常会用method 1 和 2 ,即用字符串拼接的方式加入引号。这个语法使用起来会比较麻烦,经常容易拼错引号。福音来了,自10G开始,便提供了这种以 q开头的自定义语法来自定义一个引用机制。语法为:q'[ ]'
其中[]可以随意替换成你想要的符号,比如 q'##'
ORACLE官方对此的解释是:
Quoting Mechanism for String Literals
Oracle 10g allows you to define your own string delimiters to remove the need to double up any single quotes. Any character that is not present in the string can be used as the delimiter.
SET SERVEROUTPUT ON BEGIN -- Orginal syntax. DBMS_OUTPUT.put_line('This is Tim''s string!'); -- New syntax. DBMS_OUTPUT.put_line(This is Tim's string!); DBMS_OUTPUT.put_line(This is Tim's string!); END; / This is Tim's string! This is Tim's string! This is Tim's string! PL/SL procedure successfully completed.
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10356975/viewspace-741034/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/10356975/viewspace-741034/