简体   繁体   中英

Problems creating a temporary table in mysql

I want to create a stored procedure in Mysql that removes a certain temporary table (if it exists) and then creates this temporary table in the database 'prs1'.

The procedure that I have created is this:

    CREATE PROCEDURE `CrearTablaTemporal`(table_name VARCHAR(100))
BEGIN
    SET @TablaTemporal = table_name;
    SET @sql_query1 = CONCAT('DROP temporary table if exists ',@TablaTemporal);
    PREPARE stmt1 FROM @sql_query1;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;
    
    SET @sql_query2 = CONCAT('CREATE TEMPORARY TABLE IF NOT EXISTS prs1.',@TablaTemporal,' (ean13 VarChar(13)) Engine=MyISAM');
    PREPARE stmt2 FROM @sql_query2;
    EXECUTE stmt2;
    DEALLOCATE PREPARE stmt2;
END

When I execute the stored procedure, no error appears but if I execute the following SQL sentence it tells me that the table does not exist:

When I execute the stored procedure from my project (created in Xojo) I don't get any error but I don't know how to check if it is created perfectly since from programs with Navicat, Valentina Studio, etc. when I check the database, the table doesn't exist. The question is, how do I keep the table open, insert values and retrieve the query?. I explain myself, my application has the connection open permanently to the database all the time until I close the application. In my method, I start the transaction, execute the sentence that creates the temporary table (thanks to the stored procedure) and finish the transaction. I don't close the connection to the database but then I don't know how to maintain the table.

How could I solve it, please?.

Thank you very much. Sergio

Temporary tables are only available in the session in which they were created. As soon as the connection is terminated, temporary tables are dropped.

A common usecase for using temporary tables are test frameworks, where you use temporary tables to avoid further cleanup.

Session 1:

mysql> delimiter !!
mysql> CREATE PROCEDURE CreateTable(table_name VARCHAR(100))
    -> BEGIN
    ->   SET @a:= CONCAT("CREATE OR REPLACE TEMPORARY TABLE ", table_name, " (a int)");
    ->   EXECUTE IMMEDIATE @a;
    -> END!!
Query OK, 0 rows affected (0,01 sec)

mysql> delimiter ;
mysql> select connection_id();
+-----------------+
| connection_id() |
+-----------------+
|            4118 |
+-----------------+
1 row in set (0,00 sec)

mysql> describe foobar;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| a     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0,00 sec)

Session 2:

mysql> select connection_id();
+-----------------+
| connection_id() |
+-----------------+
|            4119 |
+-----------------+
1 row in set (0,01 sec)

mysql> describe foobar;
ERROR 1146 (42S02): Table 'test.foobar' doesn't exist

So in case you need to check integrity or content of a temporary table, you need to do that either within the same connection or you have use non temporary tables.

Finally I have the solution with the help of all those who have written to me. I program in Xojo so the queries to the database are made from this program. With Georg's help I have realized that the temporary table only exists in that session and if you close it, the temporary table is deleted. This is how I solved my problem.

I have created a method with these steps:

// Start the transaction

DB.SQLExecute("START TRANSACTION")

// Drop the temporary table if it exists and if not we create it.

We must use these two SQL sentences:

'DROP temporary table if exists @TemporalTable'
'CREATE temporary table if NOT exists @TablaTemporal(field1 VarChar(13))

// OPTIONAL: check if the created time table exists (see below)

// Insert the values into the temporary table

Dim stmSQL As String 
DB.SQLExecute("START TRANSACTION")

stmSQL = "INSERT INTO @TablaTemporal(field1)"
stmSQL = stmSQL + " VALUES(?)"

Dim ps As MySQLPreparedStatement = DB.Prepare(stmSQL)
If BBDD.Error = True Then MsgBox DB.ErrorMessage
ps.BindType( 0, MySQLPreparedStatement.MYSQL_TYPE_STRING)
ps.Bind( 0, field1)
ps.SQLExecute

DB.Commit
Return Not DB.Error

//Recover the results of the consultation against the time table

Dim stmSQL As String = "SELECT * FROM @Template"
Return DB.SQLSelect( stmSQL )

//Drop the temporary table

DROP temporary table if exists 'Temporary Table

// Finish the transaction

DB.CommitTransaction

To check and verify if the temporary table exists, I have created a "stored procedure" in the MySQL database that has this code:

CREATE PROCEDURE check_table_exists(table_name VARCHAR(100))
BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' SET @err = 1;
SET @err = 0;
SET @table_name = table_name;
SET @sql_query = CONCAT('SELECT 1 FROM ',@table_name);
PREPARE stmt1 FROM @sql_query;
IF (@err = 1) THEN
SET @table_exists = 0;
ELSE
SET @table_exists = 1;
DEALLOCATE PREPARE stmt1;
END IF;
END

Then from Xojo we only have to call the procedure with this code:

Dim stmSQL As String = "CALL check_table_exists('@TableTemporal')""
ExecuteSQL(stmSQL) database

And execute this SQL query:

Dim stmSQL As String = "SELECT @table_exists"
Return DB.SQLSelect(stmSQL)

If the result is '1', the table has been created and exists; and if it is '0', the table does not exist.

I hope this can help someone... in my case it was for pure self-learning.

A greeting, Sergio

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