简体   繁体   中英

Key commands for creating temporary tables

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?

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. A TEMPORARY 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM