You are on page 1of 1

38 Chapter 1: Creating

roll back changes, and there is no automatic deletion of rows on commit. Here is
an example:
CREATE TABLE #t ( c1 INTEGER );

INSERT #t VALUES ( 1 ); -- gets rolled back


ROLLBACK;
INSERT #t VALUES ( 2 ); -- gets committed
COMMIT;
INSERT #t VALUES ( 3 ); -- gets rolled back
ROLLBACK;
SELECT * FROM #t; -- only shows row 2
If a CREATE TABLE #table_name is executed inside a stored procedure or
other compound statement using a BEGIN block, it will get automatically
dropped when that compound statement ends. If it is executed all by itself, out-
side any compound statement, the table and its data will persist until it is
explicitly deleted or dropped or the connection ends.
Temporary table names have nested scope. That means once you CREATE
a table with the same #table_name inside a compound statement, then only that
nested table will be visible until the compound statement ends. After that, the
nested table is dropped and the outer table becomes visible again.
Here is an example that shows how the same SELECT can produce differ-
ent results inside and outside the scope of a nested table; note that the CREATE
TABLE can appear anywhere inside the compound statement, but once it has
been executed the outer table is no longer visible.
CREATE TABLE #t ( c1 INTEGER );
INSERT #t VALUES ( 1 );
SELECT * FROM #t; -- displays 1

BEGIN
SELECT * FROM #t; -- still displays 1
CREATE TABLE #t ( c1 INTEGER );
INSERT #t VALUES ( 2 );
SELECT * FROM #t; -- now displays 2
END;

SELECT * FROM #t; -- displays 1 again


This form of CREATE TABLE doesnt cause an automatic COMMIT as a side
effect. That means its safe to create this kind of table inside a transaction and it
wont disrupt the commit-versus-rollback logic.

Tip: Local temporary tables arent just for stored procedures. You can create
and use them from client-side application code; for example, PowerBuilders
EXECUTE IMMEDIATE can be used to create a temporary table that you can then
reference in a DataWindow SELECT.

1.15.2.2 DECLARE LOCAL TEMPORARY TABLE


<declare_local_temporary_table> ::= DECLARE LOCAL TEMPORARY TABLE <table_name>
<table_element_list>
[ <commit_action> ]
<table_name> ::= <identifier>
With this format it doesnt matter if the table name begins with a number sign or
not; a local temporary table is created either way.

You might also like