DECLARE Statement

Syntax

DECLARE variable_identifier type DEFAULT default_value
  [UPDATE FROM '('stream_query')'];

Substitutable Fields

variable_identifier

A unique identifier (name) for the variable.

type

One of the supported StreamBase data types as described in StreamBase Data Types.

default_value

The value assigned to the variable at initialization.

stream_query

A SELECT statement, which returns a value that is assigned to the variable.

Discussion

Use the DECLARE statement to define dynamic variables. The scope of a dynamic variable in a StreamSQL application is the module (that is, the ssql file that contains the StreamSQL application). This differs from dynamic variables in EventFlow applications, where scope is limited to an operator. The stream referenced in the stream_query field can be an input, output, or a named stream. By contrast, in EventFlow applications, values assigned to dynamic variables can only come from input or output streams.

A StreamSQL variable identifier can be used in other StreamSQL statements anywhere a tuple field identifier could be used. For example, as a SELECT target list entry, in the predicate of a WHERE clause, or as a function argument.

In the following example, the dynamic variable intVar changes value each time a tuple is submitted to the input stream dynIn. In the SELECT clause that populates the output stream, the dynamic variable is used as an entry in the target list as well as in the WHERE clause predicate.

CREATE INPUT STREAM dynIn (value int);
DECLARE intVar int DEFAULT 15 UPDATE FROM
  (SELECT value from dynIn);
CREATE INPUT STREAM student (name string, address string, age int);
CREATE OUTPUT STREAM selected_students AS
  SELECT *, intVar AS minimum_age FROM student WHERE age>=intVar;

Using Dynamic Variables to Implement a Sequence Operator

You can add sequence numbers to an incoming stream in StreamSQL, much like EventFlow's Sequence operator. In StreamSQL, this feature is implemented using dynamic variables. To support this feature, you do not need to specify the initial setter stream for a dynamic variable, and you can specify one or more setter streams in later statements. The following example shows the dynamic variable addcountfield used to add the incremented field counter to the incoming stream:

CREATE INPUT STREAM Greeting (
    hello string
);
CREATE OUTPUT STREAM CountedGreetings ;

DECLARE addcountfield long DEFAULT 0L;
CREATE STREAM seqIdSetterStream (
    counter long
);
UPDATE addcountfield FROM (SELECT * FROM seqIdSetterStream);
SELECT *, addcountfield AS counter FROM Greeting INTO CountedGreetings;
SELECT addcountfield + 1 AS counter FROM Greeting INTO seqIdSetterStream;