INSERT
The INSERT statement inserts rows into a table or view or activates the INSTEAD OF INSERT trigger. The table or view can be at the current server or any DB2® subsystem with which the current server can establish a connection. Inserting a row into a view inserts the row into the table on which the view is based if no INSTEAD OF INSERT trigger is defined on the specified view. If an INSTEAD OF INSERT trigger is defined, the trigger is activated instead of the INSERT statement.
There are three forms of this statement:
- The INSERT via VALUES form is used to insert a single row into the table or view using the values provided or referenced.
- The INSERT via SELECT form is used to insert one or more rows into the table or view using values from other tables, or views, or both.
- The INSERT via FOR n ROWS form is used to insert multiple rows into the table or view using values provided or referenced. Although not required, the values can come from host-variable arrays. This form of INSERT is supported in SQL procedure applications. However, since host-variable arrays are not supported in SQL procedure applications, the support is limited to insertion of scalar values.
Invocation
This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.
Authorization
Authority requirements depend on whether the object identified in the statement is a user-defined table, a catalog table for which inserts are allowed, or a view:
When a user-defined table is identified: The privilege set must include at least one of the following:
- The INSERT privilege on the table
- Ownership of the table
- DBADM authority on the database that contains the table
- SYSADM authority
- DATAACCESS authority
If the database is implicitly created, the database privileges must be on the implicit database or on DSNDB04.
When a catalog table is identified: The privilege set must include at least one of the following:
- ACCESSCTRL authority
- DATAACCESS authority
- DBADM authority on the catalog database
- SQLADM authority
- SYSCTRL authority
- SYSADM authority
- System DBADM authority
When a view is identified: The privilege set must include at least one of the following:
- DATAACCESS authority
- INSERT privilege on the view
- SYSADM authority
The owner of a view, unlike the owner of a table, might not have INSERT authority on the view (or can have INSERT authority without being able to grant it to others). The nature of the view itself can preclude its use for INSERT. For more information, see the discussion of authority in CREATE VIEW.
If the INSERT statement is embedded in a SELECT statement, the privilege set must include the SELECT privilege on the table or view.
If a fullselect is specified, the privilege set must include authority to execute the fullselect. For more information about the authorization rules, see Authorization.
If the statement is embedded in an application program, the privilege set is the privileges that are held by the owner of the plan or package. If the statement is dynamically prepared, the privilege set is determined by the DYNAMICRULES behavior in effect (run, bind, define, or invoke) and is summarized in Table 1. (For more information on these behaviors, including a list of the DYNAMICRULES bind option values that determine them, see Authorization IDs and dynamic SQL.)
Syntax
>>-INSERT INTO--+-table-name-+--+-----------------------+-------> '-view-name--' | .-,-----------. | | V | | '-(----column-name-+--)-' >--+--------------------+--+-----------------------+------------> '-| include-column |-' '-OVERRIDING USER VALUE-' >--+-VALUES-+-+-expression-+---------+-----------------------------------------------------------------+->< | | +-DEFAULT----+ | | | | '-NULL-------' | | | | .-,--------------. | | | | V | | | | '-(---+-expression-+-+-)-' | | +-DEFAULT----+ | | '-NULL-------' | +-+-----------------------------------+--fullselect--+----------------------+--+------------------+-+ | | .-,-----------------------. | '-| isolation-clause |-' '-QUERYNO--integer-' | | | V | | | | '-WITH----common-table-expression-+-' | '-| multiple-row-insert |---------------------------------------------------------------------------'
include-column:
.-,--------------------------. V | >>-INCLUDE--(----column-name--| data-type |-+--)---------------><
data-type:
>>-+-| built-in-type |-+--------------------------------------->< '-distinct-type-----'
built-in-type:
>>-+-+-SMALLINT----+-------------------------------------------------+->< | +-+-INTEGER-+-+ | | | '-INT-----' | | | '-BIGINT------' | | .-(5,0)-------------------. | +-+-+-DECIMAL-+-+--+-------------------------+--------------------+ | | '-DEC-----' | | .-,0-------. | | | '-NUMERIC-----' '-(integer-+----------+-)-' | | '-,integer-' | | .-(53)------. | +-+-FLOAT--+-----------+--+---------------------------------------+ | | '-(integer)-' | | | +-REAL------------------+ | | | .-PRECISION-. | | | '-DOUBLE--+-----------+-' | | .-(34)-. | +-DECFLOAT--+------+----------------------------------------------+ | '-(16)-' | | .-(1)-------. | +---+-+-CHARACTER-+--+-----------+----------+--+--------------+---+ | | '-CHAR------' '-(integer)-' | '-FOR BIT DATA-' | | '-+-+-CHARACTER-+--VARYING-+--(integer)-' | | | '-CHAR------' | | | '-VARCHAR----------------' | | .-(1)-------. | +-+-GRAPHIC--+-----------+-+--------------------------------------+ | | '-(integer)-' | | | '-VARGRAPHIC--(integer)--' | | .-(1)-------. | +-+-BINARY--+-----------+---------+-------------------------------+ | | '-(integer)-' | | | '-+-BINARY VARYING-+--(integer)-' | | '-VARBINARY------' | '-+-DATE------------------------------------------------+---------' +-TIME------------------------------------------------+ | .-(--6--)-------. .-WITHOUT TIME ZONE-. | '-TIMESTAMP--+---------------+--+-------------------+-' '-(--integer--)-' '-WITH TIME ZONE----'
isolation-clause:
>>-WITH--+-RR-+------------------------------------------------>< +-RS-+ '-CS-'
multiple-row-insert:
>>-VALUES--+-+-expression----------+---------+------------------> | +-host-variable-array-+ | | +-NULL----------------+ | | '-DEFAULT-------------' | | .-,-----------------------. | | V | | '-(---+-expression----------+-+-)-' +-host-variable-array-+ +-NULL----------------+ '-DEFAULT-------------' >--+-------------------------------------+----------------------> | (1) | '-FOR--+-host-variable----+--ROWS-----' '-integer-constant-' .-ATOMIC----------------------------------. >--+-----------------------------------------+----------------->< | (2) | '-NOT ATOMIC CONTINUE ON SQLEXCEPTION-----'
- The FOR n ROWS clause must be specified for a static multiple-row-insert. However, this clause is optional for a dynamic INSERT statement. For a dynamic statement, the FOR n ROWS clause is specified on the EXECUTE statement.
- The ATOMIC or NOT ATOMIC CONTINUE ON SQLEXCEPTION clauses can be specified for a static multiple-row-insert. However, this clause must not be specified for a dynamic INSERT statement. For a dynamic statement, the ATOMIC or NOT ATOMIC CONTINUE ON SQLEXCEPTION clause is specified as an attribute on the PREPARE statement.
Description
- INTO table-name or view-name
- Identifies the object
of the INSERT statement. The name must identify a table or view that
exists at the current server. The name must not identify:
- An auxiliary table
- A catalog table
- A directory table
- A read-only view unless an instead of trigger is defined for the insert operation on the view. (For a description of a read-only view, see CREATE VIEW.)
- A view column that is derived from a constant, expression, or scalar function
- A view column that is derived from the base table column as some other column of the view
- A materialized query table
- A table that is implicitly created for an XML column
In an IMS™ or CICS® application, the DB2 subsystem that contains the identified table or view must be a remote server that supports two-phase commit.
- column-name,...
- Specifies the columns for which insert values are provided. Each
name must identify a column of the table or view. The columns can
be identified in any order, but the same column must not be identified
more than one time. A view column that cannot accept insert values
must not be identified. If the object of the INSERT statement is a
view with columns that cannot accept insert values, a list of column
names must be specified, and the list must not identify these columns.
If a qualifier is specified, it must be valid (that is, the table
name must be the table or view name specified after the INTO keyword,
and if a qualifier is specified for the table name, it must match
the default qualifier).
Omission of the column list is an implicit specification of a list in which every column of the table (that is not defined as implicitly hidden) or view is identified in left-to-right order. This list is established when the statement is prepared and therefore does not include columns that were added to the table after the statement was prepared.
The effect of a rebind on INSERT statements that do not include a column list is that the implicit list of names is re-established. Therefore, the number of columns into which data is inserted can change and cause an error.
- include-column
- Specifies a set of columns that are included, along with the columns
of table-name or view-name,
in the result table of the INSERT statement when it is nested in the
FROM clause of the outer fullselect that is used in a subselect, a
SELECT statement, or in a SELECT INTO statement. The included columns
are appended to the end of the list of columns that is identified
by table-name or view-name.
- INCLUDE
- Introduces a list of columns that is to be included in the result table of the INSERT statement. The included columns are only available if the INSERT statement is nested in the FROM clause of a SELECT statement or a SELECT INTO statement.
- column-name
- Specifies the name for a column of the result table of the INSERT statement that is not the same name as another included column nor a column in the table or view that is specified in table-name or view-name.
- data-type
- Specifies the data type of the included column. The included columns
are nullable.
- built-in-type
- Specifies a built-in data type. See CREATE TABLE for a description of each built-in type.
- distinct-type
- Specifies a distinct type. Any length, precision, or scale attributes for the column are those of the source type of the distinct type as specified by using the CREATE TYPE statement.
- OVERRIDING USER VALUE
- Specifies that the value
specified in the VALUES clause or produced by a fullselect for a column
that is defined as either GENERATED ALWAYS or GENERATED BY DEFAULT
is ignored. Instead, a system-generated value is inserted, overriding
the user-specified value.
If OVERRIDING USER VALUE is specified, the implicit or explicit list of column must include a column that is defined as either GENERATED ALWAYS or GENERATED BY DEFAULT. For example, a ROWID column, an identity column, or a row change timestamp column.
- VALUES
- Specifies
one new row in the form of a list of values. The number of values
in the VALUES clause must be equal to the number of names in the column
list and the columns that are identified in the INCLUDE clause. The
first value is inserted in the first column in the list, the second
value in the second column, and so on. If more than one value is specified,
the list of values must be enclosed in parentheses. Assignments to
included columns are only processed when the INSERT statement is nested
in the FROM clause in a SELECT statement or a SELECT INTO statement.
- expression
- Any expression of the type described in Expressions. The
expression must not include a column name. If expression is
a host variable, the host variable can identify a structure. Any host
variable or structure that is specified must be described in the application
program according to the rules for declaring host structures and variables.If expression is a host variable, it can include an indicator variable or an indicator array (in the case of a host structure). When extended indicator variables are enabled, an expression must not be more complex than a reference to a single host variable if the indicator is set to an extended indicator value of default (-5) or unassigned (-7). In addition:
- A CAST specification can be used if either of the following is
true:
- The target column is defined as nullable.
- The target column is defined as NOT NULL with a non-null default, the source of the CAST specification is a single host variable, and the data attributes (data type, length, precision, and scale) of the host variable are the same as the result of the cast specification.
- A scalar fullselect can be used if either of the following is
true for each expression in the select list of the fullselect:
- The target column that corresponds to the expression is defined as nullable.
- The expression is not more complex than a reference to a single host variable for which the indicator is set to an extended indicator value of default (-5) or unassigned (-7), or the expression is a CAST specification which would have been valid as a stand-alone expression.
- A CAST specification can be used if either of the following is
true:
- DEFAULT
- The default value that is assigned to the column. If
the column is a ROWID column, an identity column, a row-begin column,
a row-end column, or a transaction-start-ID column, DB2 will generate a value for the
column. You can specify DEFAULT only for columns that have an
assigned default value, ROWID columns, and identity columns.
For information on default values of data types, see the description of the DEFAULT clause for CREATE TABLE.
- NULL
- Specifies the null value as the value of the column. Specify NULL only for nullable columns.
If the implicit or explicit list of columns includes a ROWID, an identity column, or a row change timestamp column that was defined as GENERATED ALWAYS, you must specify DEFAULT unless you specify the OVERRIDING USER VALUE clause to indicate that any user-specified value will be ignored and a unique system-generated value will be inserted.
For a ROWID or identity column that is defined as GENERATED BY DEFAULT, you can specify a value. However, a value can be inserted into ROWID column defined BY DEFAULT only if a single-column unique index is defined on the ROWID column and the specified value is a valid row ID value that was previously generated by DB2. When a value is inserted into an identity column defined BY DEFAULT, DB2 does not verify that the specified value is a unique value for the column unless the identity column has a single-column unique index.
Although an implicitly hidden DOCID column for XML values is defined as GENERATED ALWAYS, you can include the DOCID column in the explicit list of columns and specify a value for it. However, DB2 will ignore the value.
- WITH common-table-expression
- Specifies a common table expression. For an explanation of common table expression, see common-table-expression.
- fullselect
- Specifies
a set of new rows in the form of the result table of a fullselect.
If the result table is empty, SQLCODE is set to +100, and SQLSTATE
is set to '02000'.
The base object of the INSERT statement and the base object of the fullselect or any subquery of the fullselect can be the same table. In this case, the fullselect is evaluated completely before any rows are inserted.
For an explanation of fullselect, see fullselect.
The number of columns in the result table must be equal to the number of names in the column list and the columns that are identified in the INCLUDE clause. The value of the first column of the result is inserted in the first column in the list, the second value in the second column, and so on. Any values that are produced for a generated column must conform to the rules that are described for those columns under the VALUES clause. Assignments to included columns are only processed when the INSERT statement is nested in the FROM clause of a SELECT statement or a SELECT INTO statement.
If the expression that specifies the value of a result column is a variable, the host variable can include an indicator variable. When extended indicator variables are enabled, the target column that corresponds to an expression in the select list of the fullselect that involves a host variable with an extended indicator value of default (-5) or unassigned (-7), must be defined as nullable and either of the following expressions:- The expression must not be more complex than a reference to a single host variable.
- The expression must be a CAST specification with the following
characteristics:
- The source of the CAST specification must be a single host variable.
- The data attributes (data type, length, precision, and scale) of the host variable are the same as the result of the cast specification.
If the object table is self-referencing, the fullselect must not return more than one row.
- isolation-clause
- Specifies
the isolation level that is used when the fullselect is executed.
- WITH
- Introduces the isolation level, which can be one of the following
values:
- RR
- Repeatable read
- RS
- Read stability
- CS
- Cursor stability
The default isolation level of the statement is the isolation level of the package or plan in which the statement is bound, with the package isolation taking precedence over the plan isolation. When a package isolation is not specified, the plan isolation is the default.
- QUERYNO integer
- Specifies
the number to be used for this SQL statement in EXPLAIN output and
trace records. The number is used for the QUERYNO column of the plan
table for the rows that contain information about this SQL statement.
This number is also used in the QUERYNO column of the SYSIBM.SYSSTMT
and SYSIBM.SYSPACKSTMT catalog tables.
If the clause is omitted, the number that is associated with the SQL statement is the statement number that is assigned during precompilation. Thus, if the application program is changed and then precompiled, that statement number might change.
Using the QUERYNO clause to assign unique numbers to the SQL statements in a program is helpful:
- For simplifying the use of optimization hints for access path selection
- For correlating SQL statement text with EXPLAIN output in the plan table
For information about using optimization hints, such as enabling the system for optimization hints and setting valid hint values, and for information about accessing the plan table, see Managing DB2 Performance.
multiple-row-insert
- VALUES
- Specifies
the items for the rows to be inserted. The number of items in the
VALUES clause must equal the number of names in the implicit or explicit
column list. The first item in the list provides the value (or values)
for the first column in the list. The second item in the list provides
the value (or values) for the second column, and so on.
- expression
- Any expression of the type described in Expressions. The expression must not include a column name. For each row that is inserted, the corresponding column is assigned the value of the expression.
- host-variable-array
- Each host-variable array must be defined in the application program
in accordance with the rules for declaring an array. A host-variable
array contains the data for a column of table that is a target of
the INSERT. The number of rows to be inserted must be less than or
equal to the dimension of each of the host-variable arrays.
An optional indicator array can be specified for each host-variable array. It should be specified if the SQLTYPE of any SQLVAR occurrence indicates that the SQLVAR is nullable. The indicators must be small integers. The indicator array must be large enough to contain an indicator for each row of input data.
If extended indicator variables are enabled, the extended indicator variable values of DEFAULT or UNASSIGNED can be used inside the indicator array.
- DEFAULT
- Specifies that the default value is assigned to the column. For each row inserted, the corresponding column is assigned its default value. DEFAULT can be specified only for columns that have a default value. For information on default values of data types, see the description of the DEFAULT clause for CREATE TABLE.
- NULL
- Specifies the null value as the value of the column in each row inserted. For each row inserted, the corresponding column is assigned the NULL value. Specify NULL only for nullable columns.
- FOR host-variable or integer-constant ROWS
- Specifies
the number of rows to be inserted. For a dynamic INSERT statement,
this clause can be specified on the EXECUTE statement. For more information,
see the EXECUTE
statement. However, this clause is required when a dynamic
SELECT statement contains more than one multiple-row INSERT statement.
host-variable or integer-constant is assigned to an integral value k. If host-variable is specified, it must be an exact numeric type with scale zero, and must not include an indicator variable. Furthermore, k must be in the range, 0<k<=32767. k rows are inserted into the target table from the specified source data.
If a parameter marker is specified in this clause, a value must be provided with the USING clause of the associated EXECUTE or OPEN statement.
- ATOMIC or NOT ATOMIC CONTINUE ON SQLEXCEPTION
- Specifies
whether all of the rows should be inserted as an atomic operation
or not.
- ATOMIC
- Specifies that if the insert for any row fails, all changes made to the database by any of the inserts, including changes 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 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 to complete), including any triggers that might have
been executed as a result of the INSERT statement.
This clause is only valid for a static INSERT statement. This clause must also not be specified if the INSERT statement is contained within a SELECT statement. For a dynamic INSERT statement, specify the clause on the PREPARE statement. For more information, see PREPARE.
Notes
- Insert rules:
- Insert values must satisfy the following
rules. If they do not, or if any other errors occur during the execution
of the INSERT statement, no rows are inserted and the position of
the cursors are not changed.
- Default values. The value inserted in any column that is not in the column list is the default value of the column. Columns without a default value must be included in the column list. Similarly, if you insert into a view, the default value is inserted into any column of the base table that is not included in the view. Hence, all columns of the base table that are not in the view must have a default value.
- Length. If the insert value of a column is a number, the column must be a numeric column with the capacity to represent the integral part of the number. If the insert value of a column is a string, the column must be either a string column with a length attribute at least as great as the length of the string, or a datetime column if the string represents a date, time, or timestamp.
- Assignment. Insert values are assigned to columns in accordance with the assignment rules described in Language elements.
- Uniqueness constraints. If the identified table or the base table of the identified view has one or more unique indexes, each row inserted into the table must conform to the constraints imposed by those indexes.
- Referential constraints. Each nonnull insert value of a foreign key must be equal to some value of the parent key of the parent table in the relationship.
- Check constraints. The identified table or the base table of the identified view might have one or more check constraints. Each row inserted must conform to the conditions imposed by those constraints. Thus, each check condition must be true or unknown.
- Field and validation procedures. If the identified table or the base table of the identified view has a field or validation procedure, each row inserted must conform to the constraints imposed by that procedure.
- Indexes with VARBINARY columns. If the identified table has an index on a VARBINARY column or a column that is a distinct type that is based on VARBINARY data type, that index column cannot specify the DESC attribute. To use the SQL data change operation on the identified table, either drop the index or alter the data type of the column to BINARY and then rebuild the index.
- Views and the WITH CHECK OPTION. For views defined with
WITH CHECK OPTION, each row you insert into the view must conform
to the definition of the view. If the view you name is dependent on
other views whose definitions include WITH CHECK OPTION, the inserted
rows must also conform to the definitions of those views. For an explanation
of the rules governing this situation, see CREATE VIEW.
For views that are not defined with WITH CHECK OPTION, you can insert rows that do not conform to the definition of the view. Those rows cannot appear in the view but are inserted into the base table of the view.
- Omitting the column list. When you omit the column list, you must specify a value for every column that was present in the table when the INSERT statement was bound or (for dynamic execution) prepared.
- Triggers. An INSERT statement might cause triggers to be
activated. A trigger might cause other statements to be executed or
raise error conditions based on the insert values. If
an INSERT statement for a view activates an INSTEAD OF trigger, the
validity, referential integrity, and check constraints are checked
against the data changes that are performed in the trigger, and not
against the definition of the view that activates the trigger or the
definition of the underlying tables or views. When triggers are processed for an INSERT statement that inserts multiple rows depends on the atomicity option that is in effect for the INSERT statement:
- ATOMIC. The inserts are processed as a single statement. Any statement level triggers are activated one time for the statement, and the transition tables will include all of the rows that were inserted.
- NOT ATOMIC CONTINUE ON SQLEXCEPTION. The inserts are processed
separately. Any statement level triggers are processed for each row
that is inserted, and the transition table includes the individual
row that is inserted. When errors are encountered with this option
in effect, processing continues, and some of the specified rows will
not be inserted. In this case, if an insert trigger is defined on
the underlying base table, the statement level triggers will only
be activated for rows that were successfully inserted.
Regardless of the failure of any particular source row, the INSERT statement will not undo any changes that are made to the database by the statement. Insert will be attempted for rows that follow the failed row. However, the minimum level of atomicity is at least that of a single source row (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.
- Inserting XML documents:
- When XML documents are inserted into a table that contains an XML index, the XML values that are inserted into the index are cast to the data type that is specified on the CREATE INDEX statement. If the XML value cannot be cast to the specified data type, the XML value is ignored for the XML index but the document is still inserted into the table. If the data type that is specified for casting is DECFLOAT, values can be rounded when they are inserted into the index. If the index is unique, the rounding that happens during the cast can result in duplicate values.
- Number of rows inserted:
- Normally, after an INSERT statement completes execution, the value
of SQLERRD(3) in the SQLCA is the number of rows inserted. The value
in SQLERRD(3) does not include the number of rows that were inserted
as the result of a trigger.
For a complete description of the SQLCA, including exceptions to the above statement, see SQL communication area (SQLCA).
- Nesting user-defined functions or stored procedures:
- An INSERT statement can implicitly or explicitly refer to user-defined functions or stored procedures. This is known as nesting of SQL statements. A user-defined function or stored procedure that is nested within the INSERT must not access the table into which you are inserting values.
- Locking:
- Unless appropriate locks already exist, one or more exclusive
locks are acquired at the execution of a successful insert operation.
Until a commit or rollback operation releases the locks, only the
application process that performed the insert can access the inserted
row. If LOBs are not inserted into the row, application processes
that are running with uncommitted read can also access the inserted
row. The locks can also prevent other application processes from performing
operations on the table. However, application processes that are running
with uncommitted read can access locked pages and rows.
Locks are not acquired on declared temporary tables.
- Inserting rows into a table with multilevel security :
- When you insert rows into a table with multilevel security, DB2 determines the value for the
security label column of the row according to the following rules:
- If the user (the primary authorization ID) has write-down privilege or write-down control is not enabled, the user can set the security label for the row to any valid security label. The value that is specified must be assignable to a column that is defined as CHAR(8) FOR SBCS DATA NOT NULL. If the user does not specify a value for the security label or specifies DEFAULT, the security label of the row becomes the same as the security label of the user.
- If the user does not have write-down privilege and write-down control is enabled, the security label of the row becomes the same as the security label of the user.
- Inserting rows into a table for which row or column access control is enforced:
- When an INSERT statement is issued for a table for which row or
column access control is enforced, the rules specified in the enabled
row permissions or column masks determine whether the row can be inserted.
Typically those rules are based on the authorization ID or role of
the process. The following rules describe how the enabled row permissions
and column masks are used during INSERT:
- A row to be inserted must not be effected by enabled column masks
whose columns are referenced while deriving the source values for
the row.
When a column is referenced while deriving the values of a new row, if the column has an enabled column mask, the masked value is used to derive the new values. If the object table is also column access control activated, the column mask that is applied to derive the new values must ensure that the evaluation of the access control rules defined in the column mask resolves the column to itself, not to a constant or to an expression. If the column mask does not mask the column to itself, the new value cannot be used for insert and an error is returned at run time.
If the OVERRIDING USER VALUE clause is specified, the corresponding values in the new row are ignored, and the above rule for column masks is not applicable to those values.
- If the row can be inserted, and there is a BEFORE INSERT trigger
for the table, the trigger is activated.
Within the trigger actions, the new values for insert can be modified in the transition variables. When the values return from the trigger, the final values for the new values are the ones for insert.
- A row to be inserted must conform to the enabled row permissions.
When multiple enabled row permissions are defined for a table, a row access control search condition is derived by application of the logical OR operator to the search condition in each enabled row permission. A row that conforms to the enabled row permissions is a row that if the row is inserted it can be retrieved back using the row access control search condition.
Column masks are not applicable in this process.
- If the rows can be inserted, and there is an AFTER INSERT trigger for the table, the trigger is activated.
The preceding rules are not applicable to the include-columns. The include-columns are subject to the rules for the select list because they are not the columns of the object table of the INSERT statement.
- A row to be inserted must not be effected by enabled column masks
whose columns are referenced while deriving the source values for
the row.
- Extended indicator variable usage:
- When extended indicator variables are enabled, negative indicator values that are outside the range of -1 through -7 must not be specified, and the default and unassigned extended indicator values must not be specified in contexts in which they are not supported.
- Extended indicator variables:
- In an INSERT statement, a value of unassigned has the effect of setting the column to its default value.
- Extended indicator variables and insert triggers:
- The activation of insert triggers is not affected by the use of extended indicator variables. If all columns in the implicit or explicit column list have been assigned an extended indicator value of unassigned or default, an insert where all columns have their respective default values is attempted, and, if successful, the insert trigger is activated.
- Table space data compression during an insert operation:
- If the table space is defined with the COMPRESS YES option, and data is inserted into a table in the table space, the first rows are stored uncompressed. When a DB2-determined amount of data has been inserted into the table, a compression dictionary is created and stored in the table space. The rows that are inserted into the table after the dictionary is created are stored compressed using the compression dictionary.
- Generated columns:
- A generated column that is defined as GENERATED ALWAYS should not be specified in the column-list unless the corresponding entry in the VALUES list is DEFAULT or an extended indicator that specifies that a default value is to be assigned. Specify the OVERRIDING USER VALUE clause to indicate that any user-specified value should be ignored and DB2 should assign the default value when a row is inserted.
- Inserting rows into system-period temporal tables:
- When a row is inserted into a system-period temporal table, DB2 assigns values to the following
columns as indicated:
- A row-begin column is assigned a value that is generated by reading the time-of-day clock during execution of the first data change statement in the transaction that requires a value to be assigned to a row-begin column or a transaction-start-ID column in a table. This also occurs when a row in a system-period temporal table is deleted. DB2 ensures the uniqueness of the generated values for a row-begin column across transactions. If multiple rows are inserted within a single SQL transaction, the values for the row-begin column are the same for all of the rows and are unique from the values that are generated for the column by another transaction.
- A row-end column is assigned a value for the data type of the column.
- A transaction-start-ID column is assigned a unique value per unit of work or the null value. The null value is assigned to the transaction-start-ID column if the column is nullable. Otherwise, the value is generated by reading the time-of-day clock during execution of the first data change statement in the unit of work that requires a value to be assigned to a row-begin column or transaction-start-ID column in a table. This also occurs when a row in a system-period temporal table is deleted. If multiple rows are inserted within a single SQL transaction, the values for the transaction-start-ID column are the same for all the rows and are unique from the values that are generated for the column by another unit of work.
- Inserting rows into application-period temporal tables:
- When a row is inserted into an application-period temporal table, an error is returned if the period that is defined by the begin column and end column of the application period overlap with the period that is defined by the begin column and end column of the application period for another row in the table.
- INSERT without a column list:
- An INSERT statement without a column list does not include implicitly hidden columns, so columns that are defined as implicitly hidden must have a defined default value.
- Inserting a row into catalog table SYSIBM.SYSSTRINGS:
- If the object table is SYSIBM.SYSSTRINGS, only certain values can be specified, as described in Specifying conversion procedures.
- Datetime representation when using datetime registers:
- As explained in Datetime special registers, when two or more datetime registers are implicitly or explicitly specified in a single SQL statement, they represent the same point in time. This is also true when multiple rows are inserted. When ATOMIC is in effect for the INSERT statement, the special registers are evaluated one time for the processing of the statement. If NOT ATOMIC is in effect, the special registers are evaluated as each row of source data is processed.
- Non-atomic processing of an INSERT statement:
- When NOT ATOMIC is specified the rows of source data are processed
separately. Any references to special registers, sequence expressions,
and functions in the INSERT statement are evaluated as each row of
source data is processed, Statement level triggers are activated as
each row of source data is processed.
If one or more errors occur during the execution of an insert of a row, processing continues. The row that was being inserted at the time of the error is not inserted. Execution continues with the next row to be inserted, and any other changes made during the execution of the multiple-row INSERT statement are not backed out. However, the insert of an individual row is an atomic action.
- Diagnostics information for a multiple-row INSERT statement:
- A single multiple-row INSERT statement might encounter multiple
conditions. These conditions can be errors or warnings. Use the GET
DIAGNOSTICS statement to obtain information about all of the conditions
that are encountered for one of these INSERT statements. See GET DIAGNOSTICS for
more information.
If a warning occurs during the execution of an insert of a row, processing continues.
When multiple errors or warnings occur with a non-atomic INSERT statement, diagnostic information for each row is available using the GET DIAGNOSTICS statement. The SQLSTATE and SQLCODE reflect a summary of what happened during the INSERT statement:
- SQLSTATE 01659, SQLCODE +252. All rows were inserted, but one or more warnings occurred.
- SQLSTATE 22529, SQLCODE -253. At least one row was successfully inserted, but one or more errors occurred. Some warnings might also have occurred.
- SQLSTATE 22530, SQLCODE -254. No row was inserted. One or more errors occurred while trying to insert multiple rows of data.
- SQLSTATE 429BI, SQLCODE -20252. More errors occurred that DB2 is capable of recording. Statement processing is terminated.
When ATOMIC is in effect, if an insert value violates any constraints or if any other error occurs during the execution of an insert of a row, all changes made during the execution of the multiple-row INSERT statement are backed out. The SQLCA reflects the last warning encountered.
After an INSERT statement that inserts multiple rows of data, both atomic and non-atomic, information is returned to the program through the SQLCA. The SQLCA is set as follows:
- SQLCODE contains the SQLCODE.
- SQLSTATE contains the SQLSTATE.
- SQLERRD3 contains the number of rows actually inserted. SQLERRD3 is the number of rows inserted, if this is less than the number of rows requested, then an error occurred.
- SQLWARN flags are set if they were set during any single insert operation.
The SQLCA is used to return information on errors and warnings found during a multiple-row insert. If indicator arrays are provided, the indicator variable values are used to determine if the value from the host-variable array, or NULL, will be used. The SQLSTATE contains the warning from the last data mapping error.
- Specifying the number of rows for a dynamic multiple-row INSERT statement:
- Be aware of these considerations when specifying the number of
rows to be inserted with a dynamic multiple-row INSERT statement that
uses host-variable arrays:
- The FOR n ROWS clause can be specified as part of an INSERT statement or as part of an EXECUTE statement, but not both
- In the INSERT statement, you can specify a numeric constant in the FOR n ROWS clause to indicate the number of rows to be inserted or specify a parameter marker to indicate that the number of rows will be specified with the associated EXECUTE or OPEN statement. A multiple-row INSERT statement that is contained within a SELECT statement must include a FOR n ROWS clause.
- In an EXECUTE statement, when a dynamic INSERT statement is not
contained within a SELECT statement, the number of rows can be specified
with either the FOR n ROWS clause or the USING clause of the EXECUTE
statement:
- If the INSERT statement did not contain a FOR n ROWS clause, a value for the number of rows to be inserted can be specified in the FOR n ROWS clause of the EXECUTE statement with a numeric constant or host variable.
- If a parameter marker was specified as part of a FOR n ROWS clause in the INSERT statement, a value for the number of rows must be specified with the USING clause of the EXECUTE statement.
- In an OPEN statement, when a dynamic SELECT statement contains one or more INSERT statements that have FOR n ROWS clauses with parameter markers, the values for the number of rows to be inserted (that is, the values for the parameter markers) must be specified with the USING clause of the OPEN statement.
- DRDA considerations for a multiple-row INSERT statement:
- DB2 for z/OS limits the size of user data and control
information to 10M (except for LOBs, which are processed in a different
data stream) for a single multiple-row INSERT statement using host-variable
arrays.
Multiple-row insert and fetch statements are supported by any requester or server that supports the DRDA Version 3 protocols. If an attempt is made to issue a multiple-row INSERT or FETCH statement on a server that does not support DRDA Version 3 protocols, an error occurs.
When a multiple-row INSERT statement is executed at a DB2 for z/OS requester, the number of rows being inserted at the requester might not be known in some cases. These cases include:
- The FOR n ROWS clause contains a constant value for n for either a static or dynamic INSERT statement.
- Host variables are specified on the USING clause of an EXECUTE statement for a dynamic INSERT statement.
In either case, if the number of rows that is being inserted is not known, the requester might flow more data than is required to the server. The number of rows that is actually inserted will be correct because the server knows the correct number of rows to insert. However, performance can be adversely affected. Consider the following scenario:
At the requester, when this statement is executed, the number of rows being inserted, 5, is not known. As a result, the requester will flow 10 values for serial_num and 10 values for name to the server (because the maximum number of rows that can be inserted without error is 10, which is the size of the smallest host-variable array).... long serial_num [10]; struct { short len; char data [18]; }name [20] ... EXEC SQL INSERT INTO T1 VALUES (:serial_num, :name) FOR 5 ROWS
Use the following programming techniques to avoid or minimize problems:
- Avoid using constant values for n in the FOR n ROWS clause of INSERT statements. For static INSERT statements, this technique ensures that the value for n will be known at the requester.
- For dynamic INSERT statements, use the USING DESCRIPTOR clause instead of the USING host-variables clause on the EXECUTE statement. If a USING DESCRIPTOR clause is used on the EXECUTE statement, the value for 'n' must be indicated in the DESCRIPTOR.
- If neither of the above methods can be used:
- Declare your host-variable arrays as small as possible, or indicate that the size of your host-variable arrays are the size of 'n' in your descriptor. This avoids sending large numbers of host-variable-array entries that will not be used to the server.
- Ensure that varying length string arrays are initialized to a length of 0 (zero). This minimizes the amount of data that is sent to the server.
- Ensure that decimal host-variable arrays are initialized to valid values. This avoids a negative SQLCODE from being returned if the requester encounters invalid decimal data.
- Other SQL statements in the same unit of work:
- The following statements cannot follow an INSERT statement in
the same unit of work:
- An ALTER TABLE statement that changes the data type of a column (ALTER COLUMN SET DATA TYPE)
- An ALTER INDEX statement that changes the padding attribute of an index with varying-length columns (PADDED to NOT PADDED or vice versa)
- A CREATE TABLE statement that creates an accelerator-only table.
- An INSERT, UPDATE, or DELETE statement that updates accelerator-only tables from a different accelerator.
Examples
INSERT INTO DSN8A10.EMP
VALUES ('000205','MARY','T','SMITH','D11','2866',
'1981-08-10','ANALYST',16,'F','1956-05-22',
16345,500,2300);
INSERT INTO SMITH.TEMPEMPL
SELECT *
FROM DSN8A10.EMP;
INSERT INTO SESSION.TEMPEMPL
SELECT *
FROM DSN8A10.EMP
WHERE WORKDEPT='D11';
INSERT INTO DSN8A10.EMP_PHOTO_RESUME(EMPNO, EMP_ROWID)
VALUES (:HV_ENUM, DEFAULT);
You can only insert user-specified
values into ROWID columns that are defined as GENERATED BY DEFAULT
and not as GENERATED ALWAYS. Therefore, in the above example, if you
were to try to insert a value into EMP_ROWID instead of specifying
DEFAULT, the statement would fail unless you also specify OVERRIDING
USER VALUE. For columns that are defined as GENERATED ALWAYS, the
OVERRIDING USER VALUE clause causes DB2 to
ignore any user-specified value and generate a value instead. INSERT INTO B.EMP_PHOTO_RESUME
OVERRIDING USER VALUE
SELECT * FROM DSN8A10.EMP_PHOTO_RESUME;
EXEC SQL INSERT INTO T1 FOR :hv ROWS VALUES (:hva:hvind) ATOMIC;
In
this example, :hva represents the host-variable array and :hvind represents
the array of indicator variables. Array entry | :hva1 | :hva2 |
---|---|---|
1 | 1 | 32768 |
2 | -12 | 90000 |
3 | 79 | 2 |
4 | 32768 | 19 |
5 | 8 | 36 |
6 | 5 | 24 |
7 | 400 | 36 |
8 | 73 | 4000000000 |
9 | -200 | 2000000000 |
10 | 35 | 88 |
EXEC SQL INSERT INTO T2 (C1, C2)
FOR 10 ROWS VALUES (:hva1:hvind1, :hva2:hvind2)
NOT ATOMIC CONTINUE ON SQLEXCEPTION;
After execution
of the INSERT statement, the following information will be in the
SQLCA: SQLCODE = -253
SQLSTATE = 22529
SQLERRD3 = 8
GET DIAGNOSTICS :num_rows = ROW_COUNT, :num_cond = NUMBER;
The
result of this statement is num_rows = 8 and num_cond = 2 (2 conditions). GET DIAGNOSTICS CONDITION 2 :sqlstate = RETURNED_SQLSTATE,
:sqlcode = DB2_RETURNED_SQLCODE,
:row_num = DB2_ROW_NUMBER;
The
result of this statement is sqlstate = 22003, sqlcode = -302, and
row_num = 4. GET DIAGNOSTICS CONDITION 1 :sqlstate = RETURNED_SQLSTATE,
:sqlcode = DB2_RETURNED_SQLCODE,
:row_num = DB2_ROW_NUMBER;
The
result of this statement is sqlstate = 22003, sqlcode = -302, and
row_num = 8.EXEC SQL INSERT INTO T2 (C1, C2)
FOR 8 ROWS VALUES (:hva1:hvind1, :hva2:hvind2)
NOT ATOMIC CONTINUE ON SQLEXCEPTION;
After execution
of the INSERT statement, the following information will be in the
SQLCA: SQLCODE = -253
SQLSTATE = 22529
SQLERRD3 = 6
GET DIAGNOSTICS :num_rows = ROW_COUNT, :num_cond = NUMBER;
The
result of this statement is num_rows = 68 and num_cond = 2 (2 conditions). GET DIAGNOSTICS CONDITION 2 :sqlstate = RETURNED_SQLSTATE,
:sqlcode = DB2_RETURNED_SQLCODE,
:row_num = DB2_ROW_NUMBER;
The
result of this statement is sqlstate = 22003, sqlcode = -302, and
row_num = 4.GET DIAGNOSTICS CONDITION 1 :sqlstate = RETURNED_SQLSTATE,
:sqlcode = DB2_RETURNED_SQLCODE,
:row_num = DB2_ROW_NUMBER;
The
result of this statement is sqlstate = 22003, sqlcode = -302, and
row_num = 8.-- Static INSERT statement:
DECLARE CS1 CURSOR WITH ROWSET POSITIONING FOR
SELECT *
FROM FINAL TABLE
(INSERT INTO T1 VALUES (:hva, :hvb) FOR :hvn ROWS)
WHERE C1 > :hv1 AND C2 < :hv2;
OPEN CS1;
-- Dynamic INSERT statement:
PREPARE INSSTMT FROM
'SELECT *
FROM FINAL TABLE
(INSERT INTO T1 VALUES ( ? , ? ) FOR ? ROWS)
WHERE C1 > ? AND C2 < ?';
DECLARE CS1 CURSOR WITH ROWSET POSITIONING FOR :INSSTMT;
OPEN CS1 USING :hva, :hvb, :hvn, :hv1, :hv2; (or OPEN CS1 USING DESCRIPTOR ...)
If the host-variable arrays for the multiple-row INSERT statement were to be specified using a descriptor, that descriptor (SQLDA) would have to describe all input host variables in the statement, and the order of the entries in the SQLDA should be the same as the order of the order of the host variables, host-variable arrays, and values for the FOR n ROWS clauses in the statement. For example, given the statement above, the SQLVAR entries in the descriptor must be assigned in the following order: :hvn, :hva, :hvb, :hv1, hv2. In addition, the SQLVAR entries for host-variable arrays must be tagged in the SQLDA as column arrays (by specifying a special value in part of the SQLNAME field for a host variable), and the SQLVAR entry for the number of rows value must be tagged in the SQLDA (by specifying another special value in part of the SQLNAME field for the host variable).