Creating created temporary tables
Use created temporary tables when you need to store data for only the life of an application process, but you want to share the table definition. DB2® does not perform logging and locking operations for created temporary tables. Therefore, SQL statements that use these tables can execute queries efficiently.
About this task
Each application process has its own instance of the created temporary table.
You create the definition of a created temporary table using the SQL CREATE GLOBAL TEMPORARY TABLE statement.
CREATE GLOBAL TEMPORARY TABLE TEMPPROD
(SERIAL CHAR(8) NOT NULL,
DESCRIPTION VARCHAR(60) NOT NULL,
MFGCOST DECIMAL(8,2),
MFGDEPT CHAR(3),
MARKUP SMALLINT,
SALESDEPT CHAR(3),
CURDATE DATE NOT NULL);
CREATE GLOBAL TEMPORARY TABLE TEMPPROD LIKE PROD;
The SQL statements in the previous examples create identical definitions for the TEMPPROD table, but these tables differ slightly from the PROD sample table PROD. The PROD sample table contains two columns, DESCRIPTION and CURDATE, that are defined as NOT NULL WITH DEFAULT. Because created temporary tables do not support non-null default values, the DESCRIPTION and CURDATE columns in the TEMPPROD table are defined as NOT NULL and do not have defaults.
- OPEN
- SELECT
- INSERT
- DELETE
- The application process ends.
- The remote server connection through which the instance was created terminates.
- The unit of work in which the instance was created completes.
When you run a ROLLBACK statement, DB2 deletes the instance of the created temporary table. When you run a COMMIT statement, DB2 deletes the instance of the created temporary table unless a cursor for accessing the created temporary table is defined with the WITH HOLD clause and is open.
EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM TEMPPROD;
EXEC SQL INSERT INTO TEMPPROD SELECT * FROM PROD;
EXEC SQL OPEN C1;
⋮
EXEC SQL COMMIT;
⋮
EXEC SQL CLOSE C1;
EXEC SQL DECLARE C1 CURSOR WITH HOLD
FOR SELECT * FROM TEMPPROD;
In this case, DB2 does not delete the contents of TEMPPROD
until the application ends because C1, a cursor that is defined with
the WITH HOLD clause, is open when the COMMIT statement runs. In either
case, DB2 drops the instance
of TEMPPROD when the application ends.DROP TABLE TEMPPROD;