You are on page 1of 1

Chapter 1: Creating 39

You can use DECLARE LOCAL TEMPORARY TABLE inside a proce-


dure or other compound statement, but if you do it has to go at the top with the
other DECLARE statements. The table name has nested scope: Only the inner
table will be visible until the compound statement ends, even if it has the same
name as a global permanent, global temporary, or another local temporary table
created outside the compound statement.
Here is an example showing how a local temporary table name overrides a
permanent table inside a BEGIN/END block:
CREATE TABLE t ( c1 INTEGER ); -- permanent table
INSERT t VALUES ( 1 );
SELECT * FROM t; -- displays 1

BEGIN
DECLARE LOCAL TEMPORARY TABLE t ( c1 INTEGER );
INSERT t VALUES ( 2 );
SELECT * FROM t; -- displays 2
END;

SELECT * FROM t; -- displays 1 again


The commit action clause works like it does for CREATE GLOBAL
TEMPORARY TABLE. ON COMMIT DELETE ROWS is the default, ON
COMMIT PRESERVE ROWS turns off the automatic deletion when a commit
is executed, and NOT TRANSACTIONAL causes commit and rollback com-
mands to ignore rows in this table.

Tip: Use NOT TRANSACTIONAL whenever you can, if youre interested in


performance. Temporary table changes are never recorded in the transaction
log, but they are recorded in the rollback log unless you specify NOT
TRANSACTIONAL. Performance may improve if you can eliminate the use of the
rollback log for temporary tables.

You can use DECLARE LOCAL TEMPORARY TABLE just like an executable
statement outside a compound statement. When you do that, the new table over-
rides any global permanent or global temporary table with the same name. Here
is an example that shows how DECLARE LOCAL TEMPORARY TABLE
overrides a global temporary table until the new table is explicitly dropped:
CREATE GLOBAL TEMPORARY TABLE t ( c1 INTEGER );
INSERT t VALUES ( 1 );
SELECT * FROM t; -- displays 1

DECLARE LOCAL TEMPORARY TABLE t ( c1 INTEGER );


INSERT t VALUES ( 2 );
SELECT * FROM t; -- displays 2

DROP TABLE t; -- drops the temporary table


SELECT * FROM t; -- displays 1 again
The same thing happens with a global permanent table of the same name, which
means you can temporarily redefine an existing table as a temporary one.
DECLARE LOCAL TEMPORARY TABLE doesnt cause an automatic
COMMIT as a side effect, so its safe to use inside a transaction.

You might also like