1

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

Wardiam
  • 127
  • 7
  • There is a difference between *DROP* and *CREATE*. you give a schemaname *prs1* when you create the table. is this correct ? – Bernd Buffen Sep 04 '20 at 17:14
  • It is true, but I include the name of the database to confirm that it is created in the prs1 database. I have included the DROP part later and it is true that I should also include the name of the database but what interests me is the creation of the temporary table and I can't see it – Wardiam Sep 04 '20 at 17:34
  • Temporary tables exist for the extent of the session unfortunately for you the dynamic sql session is not the same as session in which you are running the procedure. – P.Salmon Sep 05 '20 at 07:21

2 Answers2

1

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.

Georg Richter
  • 5,970
  • 2
  • 9
  • 15
  • Thank you very much Georg, With your example it's clear to me that if I want to use the temporal table I have to do everything within the same session. I don't know if you can give me an answer but I have three stages in my project: 1.Begin transaction 2.Creation of the temporal table 3.Commit transaction For your example then, I would have to put the creation of the temporal table, the insertion of the values and the retrieval of the query before the end of step 3 because at the end the table would be droped, right?. – Wardiam Sep 06 '20 at 16:03
  • What do you mean by transaction? Your temporary table was created as MyISAM, which doesn't support transactions. – Georg Richter Sep 07 '20 at 04:12
1

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

Wardiam
  • 127
  • 7