KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Whitespace matters in SQL
PRODUCT: 4D | VERSION: 11 | PLATFORM: Mac & Win
Published On: February 26, 2010

When writing 4D code in the method editor, in general, the number of spaces is not relevant, as 4D will automatically format the code and add or remove spaces where appropriate. However, 4D will not parse the characters between quotes("").

This last part needs to be taken into account when writing SQL code. This is especially true since it is a common practice to build SQL code in a text variable and then execute it using the EXECUTE IMMEDIATE command.

In SQL, whitespace characters (meaning spaces, tabs and line feed) are used to seperate the different SQL elements. So if you are going to put SQL code in text variables, then you will need to add these characters.

Here are 2 examples:

Example 1:

ARRAY LONGINT(id_al;0)
ARRAY TEXT(name_at;0)
C_TEXT($sql_code)

$sql_code:=""
$sql_code:=$sql_code+"SELECT id, name"
$sql_code:=$sql_code+"FROM mytable"
$sql_code:=$sql_code+"WHERE id > 1"
$sql_code:=$sql_code+"INTO :id_al, :name_at"

Begin SQL
    EXECUTE IMMEDIATE :$sql_code;
End SQL


The above code will generate a syntax error because the actual text variable will have the value:

"SELECT id, nameFROM mytableWHERE id > 1INTO :id_al, :name_at"

Example 2:
ARRAY LONGINT(id_al;0)
ARRAY TEXT(name_at;0)
C_TEXT($sql_code)
C_TEXT($sp)

$sp:=" "

$sql_code:=""
$sql_code:=$sql_code+"SELECT id, name"+$sp
$sql_code:=$sql_code+"FROM mytable"+$sp
$sql_code:=$sql_code+"WHERE id > 1"+$sp
$sql_code:=$sql_code+"INTO :id_al, :name_at"

Begin SQL
    EXECUTE IMMEDIATE :$sql_code;
End SQL


In this example, a space has been added and now the SQL code will execute properly because the text variable contains SQL elements that have been properly seperated with whitespace characters:

"SELECT id, name FROM mytable WHERE id > 1 INTO :id_al, :name_at"