Oracle pl-sql escape character (for a “ ' ”)

前端 未结 7 2496
灰色年华
灰色年华 2020-12-14 06:31

When I am trying to execute INSERT statement in oracle, I got SQL Error: ORA-00917: missing comma error because there is a value as Alex\'s T

相关标签:
7条回答
  • 2020-12-14 07:10

    Here is a way to easily escape & char in oracle DB

    set escape '\\'
    

    and within query write like

    'ERRORS &\\\ PERFORMANCE';
    
    0 讨论(0)
  • 2020-12-14 07:14

    you can use ESCAPE like given example below

    The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL.

    SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/';
    

    The same works inside PL/SQL:

     if( id like '%/_%' ESCAPE '/' )
    

    This applies only to like patterns, for example in an insert there is no need to escape _ or %, they are used as plain characters anyhow. In arbitrary strings only ' needs to be escaped by ''.

    0 讨论(0)
  • 2020-12-14 07:17
    SELECT q'[Alex's Tea Factory]' FROM DUAL
    
    0 讨论(0)
  • 2020-12-14 07:19

    Instead of worrying about every single apostrophe in your statement. You can easily use the q' Notation.

    Example

    SELECT q'(Alex's Tea Factory)' FROM DUAL;
    

    Key Components in this notation are

    • q' which denotes the starting of the notation
    • ( an optional symbol denoting the starting of the statement to be fully escaped.
    • Alex's Tea Factory (Which is the statement itself)
    • )' A closing parenthesis with a apostrophe denoting the end of the notation.

    And such that, you can stuff how many apostrophes in the notation without worrying about each single one of them, they're all going to be handled safely.

    IMPORTANT NOTE

    Since you used ( you must close it with )', and remember it's optional to use any other symbol, for instance, the following code will run exactly as the previous one

    SELECT q'[Alex's Tea Factory]' FROM DUAL;
    
    0 讨论(0)
  • 2020-12-14 07:23

    To escape it, double the quotes:

    INSERT INTO TABLE_A VALUES ( 'Alex''s Tea Factory' );
    
    0 讨论(0)
  • 2020-12-14 07:23

    Your question implies that you're building the INSERT statement up by concatenating strings together. I suggest that this is a poor choice as it leaves you open to SQL injection attacks if the strings are derived from user input. A better choice is to use parameter markers and to bind the values to the markers. If you search for Oracle parameter markers you'll probably find some information for your specific implementation technology (e.g. C# and ADO, Java and JDBC, Ruby and RubyDBI, etc).

    Share and enjoy.

    0 讨论(0)
提交回复
热议问题