简体   繁体   English

用于创建临时表的关键命令

[英]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? 我还应该在程序开始时添加drop命令吗?

Temporary tables are connection scoped. Temporary表是连接作用域的。 They only exist until the connection is closed. 它们仅在连接关闭之前存在。

As per documentation on Temporary tables 根据Temporary tables文档

You can use the TEMPORARY keyword when creating a table. 您可以在创建表时使用TEMPORARY关键字。 A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. TEMPORARY表仅对当前连接可见,并且在连接关闭时会自动删除。 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... 这意味着两个不同的连接可以使用相同的临时表名称,而不会彼此冲突或与现有的具有相同名称的非TEMPORARY表冲突...

If a connection is not closed but shared among users, then you have to drop it and re-create. 如果连接未关闭而是在用户之间共享,则必须drop该连接并重新创建。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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