KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: SQL comments in a built SQL statement
PRODUCT: 4D | VERSION: 12 | PLATFORM: Mac & Win
Published On: November 12, 2010

When building an SQL string to use with EXECUTE IMMEDIATE it is common to build the string in steps as show below:

C_TEXT($SQL_T)
$SQL_T :="SELECT employee_id "
$SQL_T :=$SQL_T +"FROM employees "
$SQL_T :=$SQL_T +"WHERE manager_id = 100 -- The boss "
$SQL_T :=$SQL_T +"INTO :myVar;"
Begin SQL
    EXECUTE IMMEDIATE :$SQL_T;
End SQL


As built this SQL string will create an SQL error. When including comments in SQL you must be aware of how the SQL Parser will see the code. The above string will be seen as follows:

"SELECT employee_id FROM employees WHERE manager_id = 100 -- The boss INTO :myVar;"

The SQL parser will see everything behind the two dashes (--) as an SQL comment, and thus the statement is incomplete.

There are two ways to correct the condition:
  1. Include carriage returns in the building of the SQL string thus terminating each SQL clause:
    C_TEXT($SQL_T)
    $SQL_T:="SELECT employee_id \r"
    $SQL_T:=$SQL_T+"FROM employees \r"
    $SQL_T:=$SQL_T+"WHERE manager_id = 100 -- The boss \r"
    $SQL_T:=$SQL_T+"INTO :myVar;"

  2. Change the way the SQL comment is encoded in the SQL string:
    C_TEXT($SQL_T)
    $SQL_T:="SELECT employee_id "
    $SQL_T:=$SQL_T+"FROM employees "
    $SQL_T:=$SQL_T+"WHERE manager_id = 100 /* The boss */ "
    $SQL_T:=$SQL_T+"INTO :myVar;"


    Which produces the string below:

    "SELECT employee_id FROM employees WHERE manager_id = 100 /* The boss */ INTO :myVar;"

The significant difference is that SQL comments which begins with two dashes (--) end when the line is terminated with a carriage return, comments that begin with /* end with */.