Search code examples
sqloracle-databaseescapingsqlplus

Escaping ampersand character in SQL string


I am trying to query a certain row by name in my sql database and it has an ampersand. I tried to set an escape character and then escape the ampersand, but for some reason this isn't working and I'm uncertain as to what exactly my problem is.

Set escape '\'
    select * from V1144engine.T_nodes where node_id in(
    select node2_id from V1144engine.T_edges where node1_id in(
    select node2_id from V1144engine.T_edges where node1_id in(
    select node2_id from V1144engine.T_edges where node1_id = 
      (select node_id from V1144engine.T_nodes where node_name = 'Geometric Vectors \& Matrices')))
    and edge_type_id = 1)
    and node_type_id = 1
    and node_id in (
    select node2_id from V1144engine.T_edges where node1_id =
      (select node_id from V1144engine.T_nodes where node_name = 'Algebra II')
    and edge_type_id = 2);

Solution

  • Instead of

    node_name = 'Geometric Vectors \& Matrices'
    

    use

    node_name = 'Geometric Vectors ' || chr(38) || ' Matrices' 
    

    38 is the ascii code for ampersand, and in this form it will be interpreted as a string, nothing else. I tried it and it worked.

    Another way could be using LIKE and an underline instead the '&' character:

    node_name LIKE 'Geometric Vectors _ Matrices' 
    

    The chance that you'll find some other record too, which is different in only this one character, is quite low.