Host Variables in embedded SQL applications
Embedded SQL applications can also include host variable declarations for relational SQL queries. Furthermore, a host variable can be used to contain an XQuery expression to be executed. There is, however, no mechanism for passing values to parameters in XQuery expressions.
Host variables are declared using the host language specific variable declaration syntax in a declaration section.
A declaration section is the portion of an embedded SQL application found near the top of an embedded SQL source code file, and is bounded by two non-executable SQL statements:
- BEGIN DECLARE SECTION
- END DECLARE SECTION
These statements enable the precompiler to find the variable declarations. Each host variable declaration must be used in between these two statements, otherwise the variables are considered to be only regular variables.
- All host variables must be declared in the source file within a well formed declaration section before they are referenced, except for host variables referring to SQLDA structures.
- Multiple declare sections can be used in one source file.
- Host variable names must be unique within a source file. This is because the Db2® precompiler does not
account for host language-specific variable scoping rules. As such, there is only one scope for host
variables. Note: This does not mean that the Db2 precompiler changes the scope of host variables to global so that they can be accessed outside the scope in which they are defined.
foo1(){
.
.
.
BEGIN SQL DECLARE SECTION;
int x;
END SQL DECLARE SECTION;
x=10;
.
.
.
}
foo2(){
.
.
.
y=x;
.
.
.
}x is not declared in function foo2(),
or the value of x is not set to 10 in foo2().
To avoid this problem, you must either declare x as
a global variable, or pass x as a parameter to function foo2() as
follows: foo1(){
.
.
.
BEGIN SQL DECLARE SECTION;
int x;
END SQL DECLARE SECTION;
x=10;
foo2(x);
.
.
.
}
foo2(int x){
.
.
.
y=x;
.
.
.
}