EXECUTE IMMEDIATE

The EXECUTE IMMEDIATE statement (embedded SQL only) prepares an executable statement from a character string and then immediately executes the statement.

Invocation

EXECUTE IMMEDIATE is an executable command that can only be embedded in a host language. EXECUTE IMMEDIATE cannot be dynamically prepared.

Authorization

The authorization required for EXECUTE IMMEDIATE conforms exactly with whatever authorization is needed to dynamically prepare the SQL statement indicated in the statement string argument. Consult individual SQL command descriptions in this reference for authorization requirements.

Syntax

EXECUTE IMMEDIATE 
    {string-expression | host-variable}

Parameters:

string-expression A delimited character string that can contain any valid SQL command except CLOSE, DESCRIBE, EXECUTE, EXECUTE IMMEDIATE, FETCH, INCLUDE, OPEN, PREPARE, WHENEVER, or SELECT.
host-variable Identifies a variable defined in working storage (according to the rules for declaring character string variables in the host language) that contains a valid string expression (statement string).

Description

The EXECUTE IMMEDIATE command prepares and executes non-SELECT SQL commands within a statement string. You should check the syntax of the SQL statement you plan to use before placing that statement into an EXECUTE IMMEDIATE command. This check can be performed with SQLWizard.

The statement string cannot contain parameter markers (question marks) or references to host variables. The statement cannot begin with EXEC SQL or end with END-EXEC (or a semicolon). If the SQL command appearing in the statement string is invalid, an error condition is reported to the SQLCA.

The statement string must be one of the following SQL statements:

ALTER RENAME
COMMENT ON REVOKE
COMMIT ROLLBACK
CREATE SET CURRENT DEGREE
DELETE SET CURRENT LOCALE LC_CTYPE
DROP SET CURRENT OPTIMIZATION HINT
EXPLAIN SET CURRENT PATH
GRANT SET CURRENT PRECISION
INSERT SET CURRENT RULES
LABEL ON SET CURRENT SQLID
LOCK TABLE UPDATE

Examples:

Host variables cannot be used in the string expressions.

EXEC SQL 
    EXECUTE IMMEDIATE 
    'DELETE FROM employee WHERE fname = "Elvis"'
END-EXEC

EXEC SQL 
    EXECUTE IMMEDIATE 
        'UPDATE employee 
    SET fname = "Elvis" 
    WHERE e_no = 1'
END-EXEC

Another example of EXECUTE IMMEDIATE embedded in COBOL appears below:

MOVE 'UPDATE employee SET fname = "Elvis" 
    WHERE e_no = 1' 
    TO exstr 

EXEC SQL 
    EXECUTE IMMEDIATE :exstr
END-EXEC