Execute statements with input parameters

An input parameter is a placeholder in an SQL statement that indicates that the actual value is provided at run time. You cannot list a host-variable name in the text of a dynamic SQL statement because the database server knows nothing about variables declared in the application. Instead, you can indicate an input parameter with a question mark (?), which serves as a placeholder, anywhere within a statement where an expression is valid. You cannot use an input parameter to represent an identifier such as a database name, a table name, or a column name.

An SQL statement that contains input parameters is called a parameterized statement. For a parameterized SQL statement, your program must provide the following information to the database server about its input parameters:
  • Your program must use a question mark (?) as a placeholder in the text of the statement to indicate where to expect an input parameter. For example, the following DELETE statement contains two input parameters:
    EXEC SQL prepare dlt_stmt from 
       'delete from orders where customer_num = ? \
       and order_date > ?';

    The first input parameter is defined for the value of the customer_num column and the second for the value of the order_date column.

  • Your program must specify the value for the input parameter when the statement executes with the USING clause. To execute the DELETE statement in the previous step, you can use the following statement:
    EXEC SQL execute dlt_stmt using :cust_num, :ord_date;
The statement that you use to provide an input parameter with a value at run time depends on the type of SQL statement that you execute, as follows:
  • For a non-SELECT statement (such as UPDATE, INSERT, DELETE, or EXECUTE PROCEDURE) with input parameters, the EXECUTE...USING statement executes the statement and provides input parameter values.
  • For a SELECT statement associated with a cursor or for a cursor function (EXECUTE FUNCTION), the OPEN...USING statement executes the statement and provides input parameter values.
  • For a singleton SELECT statement or for a noncursor function (EXECUTE FUNCTION), the EXECUTE...INTO...USING statement executes the statement and provides input parameter values.
When the statement executes, you can list host variables or literal values to substitute for each input parameter in the USING clause. The values must be compatible in number and data type with the associated input parameters. A host variable must also be large enough to hold the data.
Important: To use host variables with the USING clause, you must know the number of parameters in the SQL statement and their data types. If you do not know the number and data types of the input parameters at run time, you must use a dynamic-management structure with the USING clause.