Declaring variables

As discussed in Chapter 3, the precompiler automatically sets the system variables when you include SQLCA, SQLCODE, or SQLSTATE in the application program. However, you must explicitly declare host and indicator variables in a declare section before using them in Embedded SQL statements.

WARNING! The precompiler generates some variables, all of which begin with “_sql”. Do not begin your variables with “_sql”, or you may receive an error message or unreliable data.

The precompiler ignores macros and #include statements in a declare section. It processes include statements as if the contents of the included file were copied directly into the file being precompiled. The syntax for a declare section with an include statement is:

exec sql begin declare section; 
 exec sql include “filename”;
 ...
 exec sql end declare section; 

Host variable declarations must conform to the C rules for variable declarations. You need not declare all variables in one declare section, since you can have an unlimited number of declare sections in a program.

When you declare variables, you must also specify the datatype. See “Datatypes and Adaptive Server” for valid datatypes. Alternatively, use the Client-Library typedefs, such as CS_CHAR, which are declared in the cspublic.h file, in declare sections.

The following example shows two character strings defined in a declare section.

exec sql begin declare section; 
 CS_CHAR name[20]; 
 CS_CHAR type[3]; 
 exec sql end declare section; 

When declaring a host variable, you can also initialize it but only if it is a scalar variable, such as this one:

exec sql begin declare section;
     int total = 0;
 exec sql end declare section;

You cannot initialize an array in its declaration.