PREPARE

The PREPARE statement creates an executable SQL statement from a string form of the statement. The character-string form is called a statement string. The executable form is called a prepared statement.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared. It must not be specified in Java.

Authorization

The authorization rules are those defined for the dynamic preparation of the SQL statement specified by the PREPARE statement. For example, see Queries for the authorization rules that apply when a SELECT statement is prepared.

Start of changeThe statement that is prepared using only the EXPLAIN privilege cannot be executed, and only the descriptive information can be obtained for that statement.End of change

Syntax

Read syntax diagram
>>-PREPARE--statement-name-------------------------------------->

>--+----------------------------------------------+------------->
   '-INTO--descriptor-name--+-------------------+-'   
                            |        .-NAMES--. |     
                            '-USING--+-LABELS-+-'     
                                     +-ANY----+       
                                     '-BOTH---'       

>--+-+------------------------------------+--FROM--host-variable-+-><
   | |                                (1) |                      |   
   | '-ATTRIBUTES--attr-host-variable-----'                      |   
   |                         (2)                                 |   
   '-FROM--string-expression-------------------------------------'   

Notes:
  1. attr-host-variable must be a string host variable and the content must conform to the rules for attribute-string. The ATTRIBUTES clause can only be specified before host-variable.
  2. string-expression is only supported for PLI.

attribute-string

Read syntax diagram
   .-----------------------------------------------------.   
   V  (1)                                                |   
>>-------+-+-ASENSITIVE-------------+------------------+-+-----><
         | +-INSENSITIVE------------+                  |     
         | |            .-DYNAMIC-. |                  |     
         | '-SENSITIVE--+---------+-'                  |     
         |              '-STATIC--'                    |     
         +-+-NO SCROLL-+-------------------------------+     
         | '-SCROLL----'                               |     
         +-| holdability |-----------------------------+     
         +-| returnability |---------------------------+     
         +-| rowset-positioning |----------------------+     
         +-fetch-first-clause--------------------------+     
         +-+-read-only-clause-+------------------------+     
         | '-update-clause----'                        |     
         +-optimize-clause-----------------------------+     
         +-isolation-clause----------------------------+     
         |                       (2)                   |     
         +-+-FOR MULTIPLE ROWS-+-----------------------+     
         | '-FOR SINGLE ROW----'                       |     
         |                                         (3) |     
         +-+-ATOMIC------------------------------+-----+     
         | '-NOT ATOMIC CONTINUE ON SQLEXCEPTION-'     |     
         +-| concurrent-access-resolution |------------+     
         +-+-WITHOUT EXTENDED INDICATORS-+-------------+     
         | '-WITH EXTENDED INDICATORS----'             |     
         | .-CONCENTRATE STATEMENTS OFF-----------.    |     
         '-+--------------------------------------+----'     
           '-CONCENTRATE STATEMENTS WITH LITERALS-'          

Notes:
  1. The same clause must not be specified more than one time. If the options are not specified, their defaults are whatever was specified for the corresponding option in an associated statement.
  2. The FOR SINGLE ROW or FOR MULTIPLE ROWS clause must only be specified for an INSERT or a MERGE statement.
  3. The ATOMIC or NOT ATOMIC CONTINUE ON SQLEXCEPTION clause must only be specified for an INSERT statement.

holdability:

Read syntax diagram
>>-+-WITHOUT HOLD-+--------------------------------------------><
   '-WITH HOLD----'   

returnability:

Read syntax diagram
>>-+-WITHOUT RETURN-------------+------------------------------><
   |              .-TO CALLER-. |   
   '-WITH RETURN--+-----------+-'   
                  '-TO CLIENT-'     

rowset-positioning:

Read syntax diagram
>>-+-WITHOUT ROWSET POSITIONING-+------------------------------><
   '-WITH ROWSET POSITIONING----'   

Start of change

concurrent-access-resolution

End of change
Read syntax diagram
>>-+-SKIP LOCKED DATA--------+---------------------------------><
   +-USE CURRENTLY COMMITTED-+   
   '-WAIT FOR OUTCOME--------'   

Description

statement-name
Names the prepared statement. If the name identifies an existing prepared statement, that prepared statement is destroyed. The name must not identify a prepared statement that is the SELECT statement of an open cursor.
INTO
If you use INTO, and the PREPARE statement is successfully executed, information about the prepared statement is placed in the SQLDA specified by the descriptor name. Thus, the PREPARE statement:
   EXEC SQL PREPARE S1 INTO :SQLDA FROM :V1;
is equivalent to:
   EXEC SQL PREPARE S1 FROM :V1;
   EXEC SQL DESCRIBE S1 INTO :SQLDA;
descriptor-name
Identifies the SQLDA. For languages other than REXX, SQLN must be set to indicate the number of SQLVAR occurrences. See DESCRIBE for information about how to determine the number of SQLVAR occurrences to use and for an explanation of the information that is placed in the SQLDA.

See Identifying an SQLDA in C or C++ for how to represent descriptor-name in C.

USING
Indicates what value to assign to each SQLNAME variable in the SQLDA when INTO is used. If the requested value does not exist, SQLNAME is set to length 0.
NAMES
Assigns the name of the column. This is the default.
LABELS
Assigns the label of the column. (Column labels are defined by the LABEL statement.)
ANY
Assigns the column label, and, if the column has no label, the column name.
BOTH
Assigns both the label and name of the column. In this case, two or three occurrences of SQLVAR per column, depending on whether the result table contains distinct types, are needed to accommodate the additional information. To specify this expansion of the SQLVAR array, set SQLN to 2×n or 3×n, where n is the number of columns in the object being described. For each of the columns, the first n occurrences of SQLVAR, which are the base SQLVAR entries, contain the column names. Either the second or third n occurrences of SQLVAR, which are the extended SQLVAR entries, contain the column labels. If there are no distinct types, the labels are returned in the second set of SQLVAR entries. Otherwise, the labels are returned in the third set of SQLVAR entries.

A REXX SQLDA does not include the SQLN field, so you do not need to set SQLN for REXX programs.

ATTRIBUTES attr-host-variable
Specifies the attributes that are in effect if a corresponding attribute has not been specified as part of the associated statement. If attributes are specified as part of the associated statement, they are used instead of the corresponding attributes specified on the PREPARE statement. In turn, if attributes are specified in the PREPARE of a SELECT statement, they are used instead of the corresponding attributes specified on a DECLARE CURSOR statement.

Start of changeattr-host-variable must identify a host variable that is described in the program in accordance with the rules for declaring string variables. attr-host-variable must be a string variable (either fixed-length or varying-length) that has a length attribute that does not exceed 32758 bytes. Leading and trailing blanks are removed from the value of the host variable. The host variable must contain a valid attribute-string.End of change

An indicator variable can be used to indicate whether or not attributes are actually provided on the PREPARE statement. Thus, applications can use the same PREPARE statement regardless of whether attributes need to be specified or not.

The options that can be specified as part of the attribute-string are as follows:

ASENSITIVE, INSENSITIVE, SENSITIVE STATIC, or SENSITIVE DYNAMIC
Specifies the sensitivity of the cursor to inserts, updates, or deletes that made to the rows underlying the result table. The sensitivity of the cursor determines whether DB2® can materialize the rows of the result into a temporary table. The default is ASENSITIVE.
ASENSITIVE
Specifies that the cursor should be as sensitive as possible. A cursor that defined as ASENSITIVE will be either insensitive or sensitive dynamic; it will not be sensitive static. For information about how the effective sensitivity of the cursor is returned to the application with the GET DIAGNOSTICS statement or in the SQLCA, see OPEN.

Start of changeThe sensitivity of a cursor is a factor in the choice of access path. Explicitly specify the sensitivity level that you need, instead of specifying ASENSITIVE.End of change

INSENSITIVE
Specifies that the cursor does not have sensitivity to inserts, updates, or deletes that are made to the rows underlying the result table. As a result, the size of the result table, the order of the rows, and the values for each row do not change after the cursor is opened. In addition, the cursor is read-only. The SELECT statement or attribute-string of the PREPARE statement cannot contain a FOR UPDATE clause, and the cursor cannot be used for positioned updates or deletes.
SENSITIVE
Specifies that the cursor has sensitivity to changes made to the database after the result table is materialized. The cursor is always sensitive to positioned updates and deletes that are made using the same cursor. However, the select-statement of the cursor must not contain an SQL data change statement if the cursor is defined as either SENSITIVE DYNAMIC or SENSITIVE STATIC. When the current value of a row no longer satisfies the select-statement or statement-name, that row is no longer visible through the cursor. When a row of the result table is deleted from the underlying base table, the row is no longer visible through the cursor.

In addition, the cursor has sensitivity to changes made to values outside the cursor (that is, by other cursors or committed changes by other application processes). If DB2 can not make changes made outside the cursor visible to the cursor, an error is issued at OPEN CURSOR. Whether the cursor is sensitive to changes made outside this cursor depends on whether DYNAMIC or STATIC is in effect for the cursor and whether SENSITIVE or INSENSITIVE FETCH statements are used.

Whether the cursor is sensitive to newly inserted rows depends on whether DYNAMIC or STATIC is in effect for the cursor. The default is DYNAMIC.

DYNAMIC
Specifies that the result table of the cursor is dynamic in that the size of the result table can change after the cursor is opened as rows are inserted into or deleted from the underlying table, and the order of the rows can change. Inserts, deletes, and updates that are made by the same application process are immediately visible. Inserts, deletes, and updates that are made by other application processes are visible after they are committed.

All FETCH statements for sensitive dynamic cursors are sensitive to changes made by this cursor, changes made by other cursors in the same application process, and committed changes made by other application processes.

If a SENSITIVE DYNAMIC cursor is not possible, an error is returned The FETCH FIRST n ROWS ONLY clause must not be specified for the outermost fullselect for a sensitive dynamic cursor.

STATIC
Specifies that the order of the rows and size of the result table is static. The size of the result table does not grow after the cursor is opened and the rows are materialized. The order of the rows is established as the result table is materialized. Rows that are inserted into the underlying table are not added to the result table of the cursor regardless of how the rows were inserted. Rows in the result table do not move if columns in the ORDER BY clause are updated in rows that have already been materialized.

Whether the changes that are made outside the cursor are visible to the cursor depends on the type of FETCH that is used with a SENSITIVE STATIC cursor. For more information, see Considerations for FETCH statements used with a sensitive static cursor.

Using a function that is not deterministic (built-in or user-defined) in the WHERE clause of select-statement or statement-name of a SENSITIVE STATIC cursor can cause misleading results. This occurs because DB2 constructs a temporary result table and retrieves rows from this table for INSENSITIVE FETCH statements. When DB2 processes a SENSITIVE FETCH statement, rows are fetched from the underlying table and predicates are re-evaluated if they contain non-correlated subqueries. Using a function that is not deterministic can yield a different result for the re-evaluated query causing the row to no longer be considered a match.

If SENSITIVE STATIC is specified and a sensitive static cursor is not possible, then an error is returned.

If ASENSITIVE, INSENSITIVE, SENSITIVE DYNAMIC, or SENSITIVE STATIC is specified as part of the ATTRIBUTES clause, SCROLL must be specified.

SCROLL or NO SCROLL
Specifies whether the cursor is scrollable.
SCROLL
Specifies that the cursor is scrollable.
NO SCROLL
Specifies that the cursor is not scrollable.
Start of changeWITHOUT RETURN or WITH RETURNEnd of change
Start of changeSpecifies whether the result table of the cursor is intended to be used as a result set that will be returned from a procedure. If statement-name is specified, the default is the corresponding prepare attribute of the statement. Otherwise, the default is WITHOUT RETURN.
WITHOUT RETURN
Specifies that the result table of the cursor is not intended to be used as a result set that will be returned from a procedure.
Start of changeWITH RETURNEnd of change
Start of changeSpecifies that the result table of the cursor is intended to be used as a result set that will be returned from a procedure. WITH RETURN is relevant only if the PREPARE statement is contained within the source code for a procedure. In other cases, the precompiler might accept the clause, but it has not effect.

When a cursor that is declared using the WITH RETURN TO CALLER clause remains open at the end of a program or routine, that cursor defines a result set from the program or routine. Use the CLOSE statement to close a cursor that is not intended to be a result set from the program or routine. Although DB2 will automatically close any cursors that are not declared using with a WITH RETURN clause, the use of the CLOSE statement is recommended to increase the portability of applications.

For non-scrollable cursors, the result set consists of all rows from the current cursor position to the end of the result table. For scrollable cursors, the result set consists of all rows of the result table.

Start of changeTO CALLEREnd of change
Start of changeSpecifies that the cursor can return a result set to the caller of the procedure. The caller is the program or routine that executed the SQL CALL statement that invokes the procedure that contains the PREPARE statement. For example, if the caller is a procedure, the result set, is returned to the procedure. If the caller is a client application, the result set is returned to the client application.

If the statement is contained within the source code for a procedure, WITH RETURN TO CALLER specifies that the cursor can be used as a result set cursor. A result set cursor is used when the result table of a cursor is to be returned from a procedure. Specifying TO CALLER is optional.

In other cases, the clause is ignored and the cursor cannot be used as a result set cursor.

End of change
TO CLIENT
Specifies that the cursor can return a result set to the client application. This cursor is invisible to any intermediate nested procedures. If a function or trigger calls the procedure (either directly or indirectly), the result set cannot be returned to the client and the cursor will be closed after the procedure finishes.
End of change
End of change
rowset-positioning
Specifies whether rows of data can be accessed as a rowset on a single FETCH statement for this cursor.
WITHOUT ROWSET POSITIONING
Specifies that the cursor can only be used with row positioned FETCH statements.
WITH ROWSET POSITIONING
Specifies that this cursor can be used with rowset positioned or row positioned FETCH statements
fetch-first-clause
Limits the number of rows that can be fetched. It improves the performance of queries with potentially large result sets when only a limited number of rows are needed. If the clause is specified, the number of rows retrieved will not exceed n, where n is the value of the integer. An attempt to fetch n+1 rows is handled the same way as normal end of date. The value of integer must be positive and non-zero. The default is 1.

If the OPTIMIZE FOR clause is not specified, a default of OPTIMIZE FOR integer ROWS is assumed. If both the FETCH FIRST and OPTIMIZE FOR clauses are specified, the lower of the integer values from these clauses is used to influence optimization and the communications buffer size.

The FETCH FIRST clause must not be specified for the outermost fullselect for a sensitive dynamic cursor.

read-only-clause
Declares that the result table is read-only and therefore the cursor cannot be referred to in positioned UPDATE and DELETE statements.
update-clause
Identifies the columns that can updated in a later positioned UPDATE statement. Each column must be unqualified and must identify a column of the table or view identified in the first FROM clause of the fullselect. The clause must not be specified if the result table of the fullselect is read-only. The clause must also not be specified if a created temporary table is referenced in the first FROM clause of the select-statement.

If the clause is specified without a list of columns, the columns that can be updated include all the updatable columns of the table or view that is identified in the first FROM clause of the fullselect.

optimize-clause
Requests special optimization of the select-statement. If the clause is omitted, optimization is based on the assumption that all rows of the result table will be retrieved. If the clause is specified, optimization is based on the assumption that the number of rows retrieved will not exceed n, where n is the value of the integer. The clause does not limit the number of rows that can be fetched or affect the result in any way other than performance.
isolation-clause
Start of changeSpecifies the isolation level at which the select statement is executed. See isolation-clause.End of change
Start of changeconcurrent-access-resolutionEnd of change
Start of changeSpecifies the type concurrent access resolution to use for the select statement. Each clause in concurrent-access-resolution can only be specified one time. Only one of the clauses can be specified for each PREPARE statement. If none of the clauses is specified, the locking semantic depends on other attributes of the statement.
SKIP LOCKED DATA
Specifies to skip data on which incompatible locks are held by other transactions. See SKIP LOCKED DATA.
USE CURRENTLY COMMITTED
Start of changeSpecifies that DB2 can use the currently committed version of the data when the data is in the process of being updated. USE CURRENTLY COMMITTED only applies in the following cases:
  • The table that is being accessed is defined in a universal table space
  • The access is for a select-statement with an isolation level of cursor stability (CS) or read stability (RS) specified in the isolation-clause:
    • When a read transaction accesses a record that is locked by an insert transaction, both ISOLATION(CS) and ISOLATION(RS) are applicable.
    • When a read transaction accesses a record that is locked by a delete transaction only ISOLATION(CS) is applicable and only when CURRENTDATA(NO) is in effect.

USE CURRENTLY COMMITTED is ignored if used in any other context.

When this clause is specified, the setting of the subsystem parameter EVALUNC applies. If the row qualifies, this clause determines if the row is accessed or skipped.

When this clause is specified and the subsystem parameter SKIPUNCI is in effect, PREPARE uses the specification of this clause. See the Notes section for more information.

Start of changeWhen this clause is specified and XML data that does not support multiple XML versions is being selected, DB2 cannot determine whether the data has been committed. In this case, DB2 uses WAIT FOR OUTCOME behavior when accessing the data.End of change

End of change
WAIT FOR OUTCOME
Specifies that DB2 waits for the commit or rollback when encountering data that is in the process of being updated or deleted. Rows that are in the process of being inserted are not skipped.
End of change
FOR MULTIPLE ROWS or FOR SINGLE ROW
Specifies if a variable number of rows will be provided for a dynamic INSERT or MERGE statement.
FOR MULTIPLE ROWS
Specifies that multiple rows can be provided with host variable arrays on an EXECUTE statement for the statement that is being prepared. FOR MULTIPLE ROWS must only be specified for an INSERT or a MERGE statement.
FOR SINGLE ROW
Specifies that multiple rows must not be provided with host variable arrays on an EXECUTE statement for the statement that is being prepared. FOR SINGLE ROW must only be specified for an INSERT or a MERGE statement.
ATOMIC or NOT ATOMIC CONTINUE ON SQLEXCEPTION
Specifies if all rows are inserted as an atomic operation. This clause can only be specified for dynamic INSERT statements.
ATOMIC
Specifies that if the insert for any row fails, all changes that are made to the database by any of the inserts, including changes that are made by successful inserts, are undone. This is the default.
NOT ATOMIC CONTINUE ON SQLEXCEPTION
Specifies that, regardless of the failure of any particular insert of a row, the INSERT statement will not undo any changes that are made to the database by the successful inserts of other rows, and inserting will be attempted for subsequent rows. However, the minimum level of atomicity is at least that of a single insert (that is, it is not possible for a partial insert operation to complete), including any triggers that might have been activated as a result of the INSERT statement.

This clause must not be specified if the INSERT statement is contained within a SELECT statement.

For preparing the MERGE statement, atomicity is specified only on the MERGE statement itself.

Start of changeWITHOUT EXTENDED INDICATORS or WITH EXTENDED INDICATORSEnd of change
Start of changeSpecifies whether the values that are provided for indicator variables during the execution of the statement follow standard SQL semantics for indicating NULL values, or if the values can use extended indicator variables to indicate a DEFAULT or UNASSIGNED value. WITHOUT EXTENDED INDICATORS is the default.End of change
Start of changeCONCENTRATE STATEMENTS OFF or CONCENTRATE STATEMENTS WITH LITERALSEnd of change
Start of changeSpecifies whether a dynamic SQL statement that specifies literal constants will be cached as a separate unique statement entry in the dynamic statement cache instead of sharing an existing statement in the cache. Dynamic SQL statements are eligible to share an existing statement in the cache if the new statement meets all of the conditions for sharing a cached version of the same dynamic statement except that the new statement specifies one or more literal constants that are different than the cached statement.
CONCENTRATE STATEMENTS OFF
Specifies that the dynamic SQL statement that specifies literal constants will be cached as a unique statement entry if it specifies one or more constants that are different than the cached version of the same dynamic statement. CONCENTRATE STATEMENTS OFF is the default dynamic statement caching behavior.
CONCENTRATE STATEMENTS WITH LITERALS
Specifies that the dynamic SQL statement that specifies literal constants will share a cached version of the same dynamic statement that is also prepared using the CONCENTRATE STATEMENTS WITH LITERALS option if the new dynamic statement meets all of the conditions for sharing the cached statement and the constants that are specified can be reused in place of the constants in the cached statement.
End of change
FROM
Specifies the statement string. The statement string is the value of the specified string-expression or the identified variable.
host-variable
Must identify a host variable that is described in the application program in accordance with the rules for declaring string variables. If the source string is over 32KB in length, the host-variable must be a CLOB or DBCLOB variable. The maximum source string length is 2MB although the host variable can be declared larger than 2MB. An indicator variable must not be specified. In PL/I, COBOL and Assembler language, the host variable must be a varying-length string variable. In C, the host variable must not be a NUL-terminated string. In SQL PL, an SQL variable is used in place of a host variable and the value must not be null.
string-expression
string-expression is any PL/I expression that yields a string. string-expression cannot be preceded by a colon. Variables that are within string-expression that include operators or functions should not be preceded by a colon. When string-expression is specified, the precompiler-generated structures for string-expression use an EBCDIC CCSID and an informational message is returned.

Notes

Rules for statement strings:
The value of the specified statement-name is called the statement string. The statement string must be one of the following SQL statements:
ALLOCATE CURSOR
ALTER
ASSOCIATE LOCATORS
COMMENT
COMMIT
CREATE
DECLARE GLOBAL
    TEMPORARY TABLE
DELETE
DROP
EXPLAIN
FREE LOCATOR
GRANT
HOLD LOCATOR
INSERT
LABEL
LOCK TABLE
MERGE
REFRESH TABLE
RELEASE SAVEPOINT
RENAME
REVOKE
ROLLBACK
SAVEPOINT
select-statement
SET CURRENT DEGREE
SET CURRENT DEBUG MODE
SET CURRENT DECFLOAT
        ROUNDING MODE
SET CURRENT LOCALE LC_CTYPE
SET CURRENT MAINTAINED TABLE
        TYPES FOR OPTIMIZATION
SET CURRENT OPTIMIZATION HINT
SET CURRENT PRECISION
Start of changeSET CURRENT QUERY ACCELERATIONEnd of change
SET CURRENT REFRESH AGE
SET CURRENT ROUTINE VERSION
SET CURRENT RULES
SET CURRENT SQLID
SET ENCRYPTION PASSWORD
SET PATH
SET SCHEMA
Start of changeSET SESSION TIME ZONEEnd of change
SIGNAL
TRUNCATE
UPDATE
The statement string must not:
  • Begin with EXEC SQL
  • End with END-EXEC or a semicolon
  • Include references to variables
Parameter markers:
Although a statement string cannot include references to variables, it can include parameter markers. The parameter markers are replaced by the values of variables when the prepared statement is executed. A parameter marker is a question mark (?) that appears where a variable could appear if the statement string were a static SQL statement.

For an explanation of how parameter markers are replaced by values, see the EXECUTE statement, OPEN, and Dynamically executing a data change statement.

The two types of parameter markers are typed and untyped:
Typed parameter marker
A parameter marker that is specified with its target data type. A typed parameter marker has the general form:
   CAST(? AS data-type)
This invocation of a CAST specification is a "promise" that the data type of the parameter at run time will be of the data type that is specified or some data type that is assignable to the specified data type. For example, in the following UPDATE statement, the value of the argument of the TRANSLATE function will be provided at run time:
  UPDATE EMPLOYEE
    SET LASTNAME = TRANSLATE(CAST(? AS VARCHAR(12)))
   WHERE EMPNO = ?
The data type of the value that is provided for the TRANSLATE function will either be VARCHAR(12), or some data type that can be converted to VARCHAR(12). For more information, refer to Assignment and comparison.

Typed parameter markers can be used in dynamic SQL statements wherever a host variable is supported and the data type is based on the promise made in the CAST specification.

Untyped parameter marker
A parameter marker that is specified without its target data type. An untyped parameter marker has the form of a single question mark. The context in which the parameter marker appears determines its data type. For example, in the above UPDATE statement, the data type of the untyped parameter marker in the predicate is the same as the data type of the EMPNO column.

Untyped parameters markers can be used in dynamic SQL statements in selected locations where host variables are supported. Table 1, Table 2, Table 3, and Table 4 show these locations and the resulting data type of the parameter. The tables group the locations into expressions, predicates, functions, and other statements to help show where untyped parameter markers are allowed.

Table 1. Untyped parameter marker usage in expressions (including select list, CASE, and VALUES)
Location of untyped parameter marker Data type (or error if not supported)
Alone in a select list. For example:
SELECT ?
Error
Both operands of a single arithmetic operator, after considering operator precedence and the order of operation rules. Includes cases such as:
? + ? + 10
DECFLOAT(34)
One operand of a single operator in an arithmetic expression (except datetime arithmetic expressions). Includes cases such as:
? + ? * 10
The data type of the other operand
Any operand of a datetime expression. For example:
'timecol + ?' or '? - datecol'
Error
Start of changeA labeled duration in a datetime expression with a type unit other than SECONDS (the portion of a labeled duration that indicates the type of units cannot be a parameter marker).End of change Start of changeDECIMAL(15,0)End of change
Start of changeA labeled duration in a datetime expression with a type unit of SECONDS (the portion of a labeled duration that indicates the type of units cannot be a parameter marker).End of change Start of changeDECIMAL(27,12)End of change
Both operands of a CONCAT operator Error
One operand of a CONCAT operator when the other operand is any character data type except CLOB If the other operand is CHAR(n) or VARCHAR(n), where n is less than 128, the data type is VARCHAR(254 - n). In all other cases, the data type is VARCHAR(254).
One operand of a CONCAT operator when the other operand is any graphic data type except DBCLOB If the other operand is GRAPHIC(n) or VARGRAPHIC(n), where n is less than 64, the data type is VARGRAPHIC(127 - n). In all other cases, the data type is VARGRAPHIC(127).
One operand of a CONCAT operator when the other operand is any binary type except BLOB If the other operand is BINARY(n) or VARBINARY(n) where n is less than 128, the data type is VARBINARY(255-n). In all other cases, the data type is VARBINARY(255)
One operand of a CONCAT operator when the other operand is a LOB string The data type of the other operand (the LOB string)
The expression following the CASE keyword in a simple CASE expression Error
Any or all expressions following the WHEN keyword in a simple CASE expression The result of applying the Rules for result data types to the expression following CASE and the expressions following WHEN that are not untyped parameter markers
A result-expression in any CASE expression when all the other result-expressions are either NULL or untyped parameter markers. Error
A result-expression in any CASE expression when at least one other result-expression is neither NULL nor an untyped parameter marker. The result of applying the Rules for result data types to all the result-expressions that are not NULL or untyped parameter markers
Alone as a column-expression in a single-row VALUES clause that is not within an INSERT statement or the VALUES clause of in insert operation of a MERGE statement Error
Alone as a column-expression in a single-row VALUES clause within an INSERT statement The data type of the column or, if the column is defined as a distinct type, the source data type of the distinct type
Alone as a column-expression in a values-single-row or values-multiple-row clause of source-table for a MERGE statement The data type of the column of the source-table, or if the data type is a distinct type, the source data type of the distinct type. The column of the source-table must be referenced elsewhere in the MERGE statement such that its data type can be determined from the context in which it is used, and all such references must resolve to the same data type.
Alone as a column-expression in the VALUES clause of an insert operation of a MERGE statement The data type of the column or, if the column is defined as a distinct type, the source data type of the distinct type
Alone as a column-expression on the right side of assignment-clause for an update operation of a MERGE statement The data type of the column or, if the column is defined as a distinct type, the source data type of the distinct type
Alone as a column-expression on the right side of a SET clause in an UPDATE statement The data type of the column or, if the column is defined as a distinct type, the source data type of the distinct type
Table 2. Untyped parameter marker usage in predicates
Location of untyped parameter marker Data type (or error if not supported)
Both operands of a comparison operator Error
One operand of a comparison operator when the other operand is not an untyped parameter marker The data type of the other operand. If the operand has a datetime data type, the result of DESCRIBE INPUT will show the data type as CHAR(255) although DB2 uses the datetime data type in any comparisons.
All the operands of a BETWEEN predicate Error
Two operands of a BETWEEN predicate (either the first and second, or the first and third) The data type of the operand that is not a parameter marker
Only one operand of a BETWEEN predicate The result of applying the Rules for result data types on the other operands that are not parameter markers
All the operands of an IN predicate, for example, ? IN (?,?,?) Error
The first and second operands of an IN predicate, for example, ? IN (?,A,B) The result of applying the Rules for result data types on the operands in the IN list that are not parameter markers
The first operand of an IN predicate and zero or more operands of the IN list except for the first operand of the IN list, for example, ? IN (A,?,B,?) The result of applying the Rules for result data types on the operands in the IN list that are not parameter markers
The first operand of an IN predicate when the right side is a fullselect of fullselect, for example, ? IN (fullselect) The data type of the selected column
Any or all operands of the IN list of the IN predicate and the first operand of the IN predicate is not an untyped parameter marker, for example, A IN (?,A,?) The data type of the first operand (the operand on the left side of the IN list)
All the operands of a LIKE predicate The first and second operands (match-expression and pattern-expression) are VARCHAR(4000). The third operand (escape-expression) is VARCHAR(1).
The first operand of a LIKE predicate (the match-expression) when at least one other operand (the pattern-expression or escape-expression) is not an untyped parameter marker. VARCHAR(4000), VARGRAPHIC(2000), or VARBINARY(4000), depending on the data type of the first operand that is not an untyped parameter marker
The second operand of a LIKE predicate (the pattern-expression) when at least one other operand (the match-expression or escape-expression) is not an untyped parameter marker. When the pattern specified in a LIKE predicate is a parameter marker and a fixed-length character host variable is used to replace the parameter marker, specify a value for the host variable that is the correct length. If you do not specify the correct length, the select does not return the intended results. VARCHAR(4000), VARGRAPHIC(2000), or VARBINARY(4000), depending on the data type of the first operand that in not an untyped parameter marker.
The third operand of a LIKE predicate (the escape-expression) when at least one other operand (the match-expression or pattern-expression) is not an untyped parameter marker CHAR(1), GRAPHIC(1), or BINARY(1), depending on the data type of the first operand that in not an untyped parameter marker
Operand of a NULL predicate Error
Table 3. Untyped parameter marker usage in functions
Location of untyped parameter marker Data type (or error if not supported)
All arguments of COALESCE or NULLIF Error
Any argument of COALESCE or NULLIF when at least one other argument is not an untyped parameter marker The result of applying the Rules for result data types on the arguments that are not untyped parameter markers, the data type of the other argument
First argument of COLLATION_KEY VARGRAPHIC(2000)
Second argument of COLLATION_KEY VARCHAR(255)
First argument of LOWER VARCHAR(4000)
Second argument of LOWER VARCHAR(255)
Any argument other than the first argument of MAX The data type of the corresponding parameter in the function instance
Any argument other than the first argument of MIN The data type of the corresponding parameter in the function instance
Both arguments of POSSTR or POSITION VARCHAR(4000) for both arguments
One argument of POSSTR or POSITION when the other argument is a character data type VARCHAR(4000)
One argument of POSSTR or POSITION when the other argument is a graphic data type VARGRAPHIC(2000)
One argument of POSSTR or POSITION when the other argument is a BINARY or VARBINARY data type VARBINARY(4000)
One argument of POSSTR or POSITION when the other argument is a BLOB BLOB(4000)
First argument of SUBSTR or SUBSTRING VARCHAR(4000)
Second or third argument of SUBSTR or SUBSTRING INTEGER
One argument of TIMESTAMP TIME
First argument of TIMESTAMP_FORMAT VARCHAR(255)
First argument of TRANSLATE Error
Second or third argument of TRANSLATE VARCHAR(4000), VARGRAPHIC(2000), depending on whether the data type of the first argument is character or graphic
Fourth argument of TRANSLATE VARCHAR(1) or VARGRAPHIC(1), depending on whether the data type of the first argument is character or graphic
First argument of UPPER VARCHAR(4000)
Second argument of UPPER VARCHAR(255)
First argument of VARCHAR_FORMAT Start of changeTIMESTAMP WITHOUT TIME ZONEEnd of change
Unary minus Start of changeDECFLOAT(34)End of change
Unary plus Start of changeErrorEnd of change
The argument of any built-in scalar function (except those that are described in this table) Error
The argument of a built-in aggregate function Error
The argument of a user-defined scalar function, user-defined aggregate function, or user-defined table function The data type of the corresponding parameter in the function instance
Table 4. Untyped parameter marker usage in statements
Location of untyped parameter marker Data type (or error if not supported)
FOR n ROWS clause of an INSERT or MERGE statement Integer
The value on the right side of a SET clause in an UPDATE statement or the UPDATE clause of the MERGE statement The data type of the column of the source-table, or if the column is defined as a distinct type, the source data type of the distinct type. The column of the source-table must be referenced elsewhere in the MERGE statement such that its data type can be determined from the context in which it is used, and all such references must resolve to the same data type.
Start of changevalue, value1, or value2 in a period specification or period clauseEnd of change Start of changeThe data type of the columns of the period referenced in the period specification or period clauseEnd of change
Considerations for FETCH statements used with a sensitive static cursor:
Whether changes made outside the cursor are visible to the cursor depends on the type of FETCH that is used with a SENSITIVE STATIC cursor:
  • A SENSITIVE FETCH is sensitive to all updates and deletes that are made by this cursor (including changes made by triggers) and committed updates and deletes by all other application processes because every fetched row is retrieved from the underlying base table and not a temporary table. This is the default type of FETCH statement for a SENSITIVE cursor.

    Changes that are made to the underlying data using this cursor result in an automatic refresh of the row. The changes that are made using this type of cursor can result in holes in the result table of the cursor. In addition, re-fetching rows (fetching rows that have already been retrieved) can result in holes in the result table. If a sensitive FETCH is issued to re-fetch a row and the row no longer qualifies for the search condition of the query, it results in a "delete hole" or an "update hole". In this case, no data is returned, and the cursor is left positioned on the hole.

  • An INSENSITIVE FETCH is not sensitive to updates and deletes that are made outside this cursor; however, it is sensitive to all updates and deletes that are made by this cursor. Changes that made with triggers are not visible with an INSENSITIVE FETCH until the content of the rows are updated in the result table with a SENSITIVE FETCH statement. If an application does not want to be sensitive to changes that are made outside this cursor (that is, the application does not want to see changes made either with another cursor or by another application process), INSENSITIVE can be explicitly specified as part of the FETCH statement for a SENSITIVE STATIC cursor. This type of FETCH is useful for refreshing data in user data buffers. For more information, see INSENSITIVE.
Error checking:
When a PREPARE statement is executed, the statement string is parsed and checked for errors. If the statement string is invalid, a prepared statement is not created and the error condition that prevents its creation is reported in the SQLCA.

In local and remote processing, the DEFER(PREPARE) and REOPT(ALWAYS)/REOPT(ONCE) bind options can cause some SQL statements to receive "delayed" errors. For example, DESCRIBE, EXECUTE, and OPEN might receive an SQLCODE that normally occurs during PREPARE processing.

Reference and execution rules:
Prepared statements can be referred to in the following kinds of statements, with the following restrictions:
Type of statement Restriction for prepared statement
DESCRIBE no restriction
DECLARE CURSOR Statement must be SELECT when the cursor is opened
EXECUTE Statement must not be SELECT

A prepared statement can be executed many times. Indeed, if a prepared statement is not executed more than once and does not contain parameter markers, it is more efficient to use the EXECUTE IMMEDIATE statement rather than the PREPARE and EXECUTE statements.

Prepared statement persistence:
All prepared statements created by a unit of work are destroyed when the unit of work is terminated, with the following exceptions:
  • A SELECT statement whose cursor is declared with the option WITH HOLD persists over the execution of a commit operation if the cursor is open when the commit operation is executed.
  • SELECT, INSERT, UPDATE, MERGE, and DELETE statements that are bound with KEEPDYNAMIC(YES) are kept past the commit point if your system is enabled for dynamic statement caching, and none of the following are true:
    • SQL RELEASE has been issued for the site
    • Bind option DISCONNECT(AUTOMATIC) was used
    • Bind option DISCONNECT(CONDITIONAL) was used and there are no hold cursors for the site
Scope of a statement name:
The scope of a statement-name is the same as the scope of a cursor-name. See DECLARE CURSOR for more information about the scope of a cursor-name.
Preparation with PREPARE INTO and REOPT bind option:
If bind option REOPT(ALWAYS) or REOPT(ONCE) is in effect, PREPARE INTO is equivalent to a PREPARE and a DESCRIBE being performed. If a statement has input variables, the DESCRIBE causes the statement to be prepared with default values, and the statement must be prepared again when it is opened or executed. When REOPT(ONCE) is in effect, the statement is always prepared twice even if there are no input variables. Therefore, to avoid having a statement prepared twice, avoid using PREPARE INTO when REOPT(ALWAYS) or REOPT(ONCE) is in effect.
Relationship of cursor attributes on PREPARE statements and SELECT or DECLARE CURSOR statements:
Cursor attributes that are specified as part of the select-statement are used instead of any corresponding options that specified with the ATTRIBUTES clause on PREPARE. Attributes that are specified as part of the ATTRIBUTES clause of PREPARE take precedence over any corresponding option that is specified with the DECLARE CURSOR statement. The order for using cursor attributes is as follows:
  • SELECT (highest priority)
  • PREPARE statement ATTRIBUTES clause
  • DECLARE CURSOR (lowest priority)
For example, assume that host variable MYQ has been set to the following SELECT statement:
      SELECT WORKDEPT, EMPNO, SALARY, BONUS, COMM
           FROM EMP
          WHERE WORKDEPT IN ('D11', 'D21')
          FOR UPDATE OF SALARY, BONUS, COMM
If the following PREPARE statement were issued, then the FOR UPDATE clause specified as part of the SELECT statement would be used instead of the FOR READ ONLY clause specified with the ATTRIBUTES clause as part of the PREPARE statement. Thus, the cursor would be updatable.
     attrstring = 'FOR READ ONLY';
     EXEC SQL PREPARE stmt1 ATTRIBUTES :attrstring FROM :MYQ;
Start of changeEffect of the CURRENT EXPLAIN MODE special register:End of change
Start of changeIf the CURRENT EXPLAIN MODE special register is set to EXPLAIN, the statement is prepared for explain only and is not executable, unless the statement is a SET statement. Attempting to execute the prepared statement will return an error. See the CURRENT EXPLAIN MODE special register for more information.End of change
Precedence of attributes for SELECT and UPDATE WHERE CURRENT OF for positioned updates:
If an UPDATE WHERE CURRENT OF statement and the associated SELECT statement are both prepared and both statements have the same PREPARE attributes, the values of the PREPARE attributes for the UPDATE WHERE CURRENT OF statement override the values of the PREPARE attributes for the SELECT statement.
Effect of extended indicator PREPARE attributes on dynamically executed positioned updates:
If an UPDATE statement with the WHERE CURRENT OF clause and the associated SELECT statement are both prepared, if extended indicator variables are used depends on the WITH EXTENDED INDICATORS or WITHOUT EXTENDED INDICATORS attributes in each of the PREPARE statements.
Table 5. Interaction between EXTENDED INDICATOR attributes of PREPARE statements for SELECT and UPDATE statements
Extended indicator attribute of PREPARE for SELECT statement Extended indicator attribute of PREPARE for UPDATE statement with WHERE CURRENT OF clause Result
WITH EXTENDED INDICATORS WITH EXTENDED INDICATORS The PREPARE attributes of the UPDATE statement override the PREPARE attributes of the SELECT statement. Non-updatable columns can be in the select-list.
WITH EXTENDED INDICATORS WITHOUT EXTENDED INDICATORS The UPDATE statement is executed without extended indicator parameters.
WITH EXTENDED INDICATORS Default (without attribute specified) The PREPARE attributes of the SELECT statement override the default PREPARE attributes for the UPDATE statement. Non-updatable columns can be in the select-list.
WITHOUT EXTENDED INDICATORS WITH EXTENDED INDICATORS The PREPARE attributes of the UPDATE statement override the PREPARE attributes of the SELECT statement. Non-updatable columns are not in the implicit or explicit select-list.
WITHOUT EXTENDED INDICATORS WITHOUT EXTENDED INDICATORS The UPDATE statement is executed without extended indicator parameters.
WITHOUT EXTENDED INDICATORS Default (without attribute specified) The PREPARE attributes of the SELECT statement override the default PREPARE attributes for the UPDATE statement. The UPDATE statement is executed without extended indicator parameters.
Default (without attribute specified) WITH EXTENDED INDICATORS The PREPARE attributes of the UPDATE statement override the PREPARE attributes of the SELECT statement. Non-updatable columns are not in the implicit or explicit select-list.
Default (without attribute specified) WITHOUT EXTENDED INDICATORS The PREPARE attributes of the UPDATE statement override the PREPARE attributes of the SELECT statement. The UPDATE statement is executed without extended indicator parameters.
Default (without attribute specified) Default (without attribute specified) The UPDATE statement is executed without extended indicator parameters.
Interactions between the SKIPUNCI subsystem parameter and the PREPARE statement:
When the PREPARE statement is specified with either the CURRENTLY COMMITTED or WAIT FOR OUTCOME clauses and the subsystem parameter SKIPUNCI is in effect, the following table describes whether uncommitted inserts are skipped, or if the transaction will wait until a commit or rollback before completing:
Table 6. Interaction between SKIPUNCI subsystem parameter and PREPARE statement
Value of SKIPUNCI
subsystem parameter
PREPARE statement attributeworking
Skip uncommitted inserts,
or wait for commit
or rollback
YES CURRENTLY COMMITTED Skip
YES WAIT FOR OUTCOME Wait
YES Not specified Skip
NO CURRENTLY COMMITTED Skip
NO WAIT FOR OUTCOME Wait
NO Not specified Wait
Extended indicator variables and deferred error checks:
When extended indicator variables are enabled, the indicator value of unassigned causes the associated target column to be omitted from the statement. Because of that, validation that is normally done in statement preparation (to recognize an INSERT into, or UPDATE of, a non-updatable column) is deferred until statement execution. If statement validation fails, an error is returned when the statement is run, not when the statement is prepared.
Reuse of prepared statements in the dynamic statement cache with CONCENTRATE STATEMENTS WITH LITERALS
To be eligible for reuse of constants, the constants in both the new statement and the cached statement must have the same:
  1. immediate usage context
  2. data type
  3. data type length and size

If DB2 determines that both instances of the constant meet the criteria for reuse, a cached statement that is prepared using the CONCENTRATE STATEMENTS WITH LITERALS option can be shared by the same SQL statement with different constants. Even though the new dynamic SQL statement will share the cached statement, the new statement will use its own literal constants when the statement is run, not the constants of the cached statement.

There are some exceptions. For example, the built-in function SUBSTR, for which, because of the immediate usage context, constant reuse in the cached statement that uses a different constant value can not be done without the risk of returning incorrect output or results. In such cases, only an SQL statement instance with the exact same constant value as the cached version of the statement is eligible for reuse. DB2 determines when and where this immediate usage context restriction applies.

Start of changeWhen the CONCENTRATE STATEMENTS WITH LITERALS option is specified, DB2 considers the values of the literal constants for access path selection only for statements that are bound with the REOPT(ONCE) or REOPT(AUTO) bind options.End of change

The DECFLOAT defined constants NAN, SNAN, and INFINITY can qualify for literal constant reuse.

The following examples show how PREPARE is used with CONCENTRATE STATEMENTS WITH LITERALS. X, Y, and Z are columns of defined as DECIMAL data type:
DECLARE C1 CURSOR
	FOR DYNSQL_WITH_LITERAL;

DYNSQL_SELECT = ‘SELECT X, Y, Z 
								FROM TABLE1 
								WHERE X < 9';

attrstring = ‘CONCENTRATE STATEMENTS WITH LITERALS';

EXEC SQL PREPARE DYNSQL_WITH_LITERAL 
	ATTRIBUTES :attrstring 
	FROM :DYNSQL_SELECT;

EXEC SQL OPEN C1;
DYNSQL_INSERT = ‘INSERT INTO 
								TABLE1 (X, Y, Z) 
								VALUES (8,109,29)';

attrstring = ‘CONCENTRATE STATEMENTS WITH LITERALS';

EXEC SQL PREPARE DYNSQL_INSERT_WITH_LITERAL
	 ATTRIBUTES :attrstring
	 FROM :DYNSQL_INSERT;

EXEC SQL EXECUTE DYNSQL_INSERT_WITH_LITERAL;

Examples

Example 1: In this PL/I example, an INSERT statement with parameter markers is prepared and executed. Before execution, values for the parameter markers are read into the host variables S1, S2, S3, S4, and S5.
   EXEC SQL PREPARE DEPT_INSERT FROM
     'INSERT INTO DSN8A10.DEPT VALUES(?,?,?,?,?)';
   -- Check for successful execution and read values into host variables
   EXEC SQL EXECUTE DEPT_INSERT USING :S1, :S2, :S3, :S4, :S5;
Example 2: Prepare a dynamic SELECT statement specifying the attributes of the cursor with a host variable on the PREPARE statement. Assume that the text of the SELECT statement is in a variable named stmttxt, and that the attributes of the cursor are in a variable named attrvar.
     EXEC SQL DECLARE mycursor CURSOR FOR mystmt;
     EXEC SQL PREPARE mystmt ATTRIBUTES :attrvar
                 FROM :stmttxt;
     EXEC SQL DESCRIBE mystmt INTO :mysqlda;
     EXEC SQL OPEN mycursor;
     EXEC SQL FETCH FROM mycursor USING DESCRIPTOR :mysqlda;
1 The scrollability and sensitivity of the cursor are independent and do not have to be specified together. Thus, the cursor might be defined as SCROLL INSENSITIVE, but the PREPARE statement might specify SENSITIVE STATIC as an override for the sensitivity.