简体   繁体   English

在mysql中创建临时表的问题

[英]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'.我想在 Mysql 中创建一个存储过程,它删除某个临时表(如果存在),然后在数据库“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:当我执行存储过程时,没有出现错误,但是如果我执行以下 SQL 语句,它告诉我该表不存在:

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.当我从我的项目(在 Xojo 中创建)中执行存储过程时,我没有收到任何错误,但我不知道如何检查它是否完美创建,因为从 Navicat、Valentina Studio 等程序中,当我检查数据库,该表不存在。 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:第 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:第 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.我在 Xojo 中编程,所以对数据库的查询是通过这个程序进行的。 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.在 Georg 的帮助下,我意识到临时表只存在于该会话中,如果关闭它,临时表将被删除。 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:我们必须使用这两个 SQL 语句:

'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:为了检查和验证临时表是否存在,我在具有以下代码的 MySQL 数据库中创建了一个“存储过程”:

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:然后从 Xojo 我们只需要使用以下代码调用过程:

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

And execute this SQL query:并执行此 SQL 查询:

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

If the result is '1', the table has been created and exists;如果结果为'1',则表已创建并存在; and if it is '0', the table does not exist.如果它是'0',则该表不存在。

I hope this can help someone... in my case it was for pure self-learning.我希望这可以帮助某人......就我而言,它是纯粹的自学。

A greeting, Sergio问候,塞尔吉奥

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

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