PL/SQL, how to escape single quote in a string?

2019-01-03 16:19发布

In the Oracle PL/SQL, how to escape single quote in a string ? I tried this way, it doesn't work.

declare
  stmt varchar2(2000);
begin
  for i in 1021 .. 6020
  loop
    stmt := 'insert into MY_TBL (Col) values(\'ER0002\')';

    dbms_output.put_line(stmt);
    execute immediate stmt;
    commit;
  end loop;
exception
  when others then
    rollback;
    dbms_output.put_line(sqlerrm);
end;
/

标签: oracle plsql
3条回答
劳资没心,怎么记你
2楼-- · 2019-01-03 16:44

In addition to DCookie's answer above, you can also use chr(39) for a single quote.

I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.

Here's a very simple example:

Select 'UPDATE Customers SET LName = ' || chr(39) || 'Doe' || chr(39) || ';' From dual;
查看更多
做个烂人
3楼-- · 2019-01-03 16:57

You can use literal quoting:

stmt := q'[insert into MY_TBL (Col) values('ER0002')]';

Documentation for literals can be found here.

Alternatively, you can use two quotes to denote a single quote:

stmt := 'insert into MY_TBL (Col) values(''ER0002'')';

The literal quoting mechanism with the Q syntax is more flexible and readable, IMO.

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-03 17:11

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

查看更多
登录 后发表回答