Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping single quote in PLSQL

Tags:

oracle

plsql

I want PLSQL to generate strings like:

COMMENT ON COLUMN TABLE.COLUMN IS 'comment from database'; 

My solution is:

declare   str_comment varchar2(4000); begin   for rec in (select table_name, column_name, description from description_table)   loop     str_comment:='COMMENT ON COLUMN '||rec.table_name||'.'||rec.column_name||'  IS '''||rec.description||'''; ' ;     dbms_output.put_line(str_comment);   end loop; end; 

Output is OK when it doesn't contain single qoutes in rec.description. Otherwise there is need for escape letter. How should I implement it?

OK output line (It's has escape letter to preserve single qoute):

COMMENT ON COLUMN TABLE1.COLUMN1_LV  IS 'It''s secret'; 

NOT NOK output line because no escape letter for single quote added and doesn't compile:

COMMENT ON COLUMN TABLE1.COLUMN1_LV  IS 'It's secret'; 

My solution is not to check if description contains single quotes. I just replace source (description) column's single quote by two single quotes before generating COMMENT ON strings and then I ROLLBACK.

Any better solution?

like image 815
reforrer Avatar asked Jul 13 '11 11:07

reforrer


People also ask

How do you escape a single quote in PL SQL?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

How do you escape a single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

How do I escape a character in PL SQL?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped.

How do you replace single quotes with double quotes in Oracle?

Try function Replace: to add a ' - single quote to a string you have to duplicate it : '' - note these are two single quotes, not a double quote. Note I had to double quote the value in 'my ''string ' - also - as yours is in your field then no worries.


1 Answers

I do this sort stuff a fair bit (usually generating insert/update statements).

You just need to use the replace function to turn all the ' into ''. i.e. Change it to:

str_comment:='COMMENT ON COLUMN '||rec.table_name||'.'||rec.column_name             ||' IS '''||REPLACE( rec.description,'''','''''')||'''; ' ; 
like image 122
Sodved Avatar answered Oct 05 '22 03:10

Sodved