How can I store sql statements in an oracle table?

oracle, select, sql

Solution

From Oracle 10G on there is an alternative to doubling up the single quotes:

insert into mytable (mycol) values (q'"select * from table where col = 'col'"');

I used a double-quote character ("), but you can specify a different one e.g.:

insert into mytable (mycol) values (q'@select * from table where col = 'col'@');

The syntax of the literal is:

q'<special character><your string><special character>'

It isn't obviously more readable in a small example like this, but it pays off with large quantities of text e.g.

insert into mytable (mycol) values (
   q'"select empno, ename, 'Hello' message
   from emp
   where job = 'Manager'
   and name like 'K%'"'
);

Problem

We need to store a select statement in a table ``` select * from table where col = 'col' ``` But the single quotes messes the insert statement up. Is it possible to do this somehow?

Original source