The EVAL statement takes a character value, interprets it as an SQL statement, and processes it.
The EVAL function (also described here) takes a character value, but interprets it as an ESQL expression that returns a value.
EVAL takes one parameter in the form of an expression, evaluates this expression, and casts the resulting value to a character string if it is not one already. The expression that is passed to EVAL must therefore be able to be represented as a character string.
In the following examples, A and B are integer scalar variables, and scalarVar1 and OperatorAsString are character string scalar variables.
The expression A+B is acceptable because, although it returns an integer value, integer values are representable as character strings, and the necessary cast is performed before EVAL continues with its second stage of evaluation.
The semicolon included at the end of the final string literal is necessary, because if EVAL is being used in place of an ESQL statement, its first stage evaluation must return a string that represents a valid ESQL statement, including the terminating semicolon.
Variables declared within an EVAL statement do not exist outside that EVAL statement. In this way EVAL is similar to a function, in which locally-declared variables are local only, and go out of scope when the function is exited.
The real power of EVAL is that it allows you to dynamically construct ESQL statements or expressions. In the second and third examples above, the value of scalarVar1 or operatorAsString can be set according to the value of an incoming message field, or other dynamic value, allowing you to effectively control what ESQL is executed without requiring a potentially lengthy IF THEN ladder.
However, consider the performance implications in using EVAL. Dynamic construction and execution of statements or expressions is necessarily more time-consuming than simply executing pre-constructed ones. If performance is vital, you might prefer to write more specific, but faster, ESQL.
In this example, EVAL is being used to replace a field reference, not an expression.
In this example, the (SELECT T.x FROM Database.y) passed to EVAL returns a list, which is not representable as a character string.
SET OutputRoot.XMLNS.Data.Result[] = EVAL('(SELECT T.x FROM Database.y AS T)');