The Q-quote mechanism

In Oracle, you quote string literals in single quotes. If you have single quotes inside that string literal, you have to escape each single quote with another single quote. But, did you know that, in 10gR2, there is an alternative approach, called the “Q-quote mechanism”?. I only knew about it when Martin mentioned it on OraQA.

Examples of the classic way:

SQL> select 'name LIKE ''%DBMS_%%'''
  2  from dual
  3  /

'NAMELIKE''%DBMS_%%'
--------------------
name LIKE '%DBMS_%%'

SQL> select 'Data,'' he said, ''Make it so.'''
  2  from dual
  3  /

'DATA,''HESAID,''MAKEITSO.'''
-----------------------------
Data,' he said, 'Make it so.'

SQL> select 'name like ''['''
  2  from dual
  3  /

'NAMELIKE''['
-------------
name like '['

From the Oracle documentation: The Q-quote mechanism, enables you to specify q or Q followed by a single quote and then another character to be used as the quote delimiter. The Q-quote delimiter can be any single- or multibyte character except space, tab, and return. If the opening quote delimiter is a [, {, <, or ( character, then the closing quote delimiter must be the corresponding ], }, >, or ) character. In all other cases, the opening and closing delimiter must be the identical character.

For example:

SQL> select q'(name LIKE '%DBMS_%%')'
  2  from dual
  3  /

Q'(NAMELIKE'%DBMS_%%
--------------------
name LIKE '%DBMS_%%'

SQL> select q'<'Data,' he said, 'Make it so.'>'
  2  from dual
  3  /

Q'<'DATA,'HESAID,'MAKEITSO.'>'
------------------------------
'Data,' he said, 'Make it so.'

SQL> select q'"name like '['"'
  2  from dual
  3  /

Q'"NAMELIKE'[
-------------
name like '['

Now, why would someone use this new q-quote mechanism instead of the classic one? Is it more readable to you when you want to escape single quotes inside a string literal?


Possibly related:


Tagged , | Post a Comment