110 Modernizing IBM Eserver iSeries Application Data Acess - A Roadmap Cornerstone
7.9.1 Defining the character string containing the SQL statement
The character field to hold the SQL command can be defined as a Single Byte Character with
fixed or varying length or as a Double Byte Character with fixed or varying length. The
character string must be an executable SQL statement, which means that not only the correct
syntax, but also the integrated variables must be converted.
Character strings must be embedded in single quotation marks (‘’).
To integrate a single quotation mark into a string, you have to double it. Do not use an Hex
value instead, because this can cause problems when using different EBCDIC codes.
Date and Time fields must be converted into a character string. The character
representation requires a four-digit year format. Then the SQL scalar functions DATE or
TIME must be used to convert these character strings into valid dates.
7.9.2 The EXECUTE IMMEDIATE statement
With EXECUTE IMMEDIATE, the command string is converted and executed in a single SQL
statement. It is a combination of the PREPARE and EXECUTE statements. It can be used to
prepare and execute SQL statements that contain neither host variables nor parameter
markers.
When an EXECUTE IMMEDIATE statement is executed, the specified statement string is
parsed and checked for errors. If the SQL statement is not valid, it is not executed and the
error condition that prevents its execution is reported in the stand-alone SQLSTATE and
SQLCODE. If the SQL statement is valid, but an error occurs during its execution, that error
condition is reported in the stand-alone SQLSTATE and SQLCODE. Additional information
on the error can be retrieved from the SQL Diagnostics Area (or the SQLCA).
In Example 7-35, the Order Header table with order date from the previous year and the
appropriate Order Detail rows are saved in history tables. The names of the history tables are
dynamically built. The year of the stored order data is part of the table name. In the create
table statement the table is not only built but filled with the appropriate data.
Order Header and Order Detail rows are deleted by using static SQL.
Example 7-35 Using the EXECUTE IMMEDIATE statement
D PrevYear S 4P 0
D MySQLString S 32740A varying
*-----------------------------------------------------------------------------------------
/Free
PrevYear = %SubDt(%Date(): *Years) - 1;
MyFile = 'ORDDTL' + %Char(PrevYear);
MySQLString = 'Create Table ' + %Trim(MyLib) + '/' + %Trim(MyFile) +
' as (Select d.* +
from ORDHDR h join ORDDTL d +
on h.OrHNbr = d.OrHNbr +
and year(ORHDTE)= '+ %Char(PrevYear)+')+
with Data';
/End-Free
C/EXEC SQL Execute Immediate :MySQLString
C/End-Exec
C/EXEC SQL
C+ Delete from ORDDTL d
C+ Where d.OrHNbr in (select h.OrHNbr
C+ from ORDHDR h