Reputation: 7906
I am creating temporary tables in stored procedures. Wanted to know what commands to include in procedure to avoid conflicts?
i usually use below syntax
CREATE TEMPORARY TABLE IF NOT EXISTS temp_shipmentcount
and use
drop command at end.
should i add drop command at beginning of procedure also?
Upvotes: 1
Views: 55
Reputation: 23992
Temporary
tables are connection scoped. They only exist until the connection is closed.
As per documentation on Temporary tables
You can use the
TEMPORARY
keyword when creating a table. ATEMPORARY
table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY
table of the same name...
If a connection is not closed but shared among users, then you have to drop
it and re-create. But dropping a database object using a shared connection will result issues.
It would be a better option to use temporary tables with runtime generated names within a stored procedure. This is safe on using shared connection objects too.
Exampe:
set @temp_table_name := concat( 'temp_table_', ( CURRENT_TIMESTAMP + 0 ) );
set @sql := concat( 'create temporary table ', @temp_table_name );
set @select_stmt := concat( 'select this', blah, blah );
set @sql := concat( @sql, ' as ' , @select_stmt );
prepare stmt from @sql;
execute stmt;
drop prepare stmt;
-- perform opearations on temp table
--
-- in between here
--
-- and then drop it before leaving
set @drop_temp := concat( 'drop temporary table ', @temp_table_name );
prepare stmt from @drop_temp;
execute stmt;
drop prepare stmt;
Upvotes: 1