简体   繁体   English

如何理解存储过程中已经存在一个mysql临时表?

[英]How to understand a mysql temporary table already exists in a stored procedure?

I use mysql temporary table to share some middle data between several stored procedures.我使用mysql临时表在几个存储过程之间共享一些中间数据。 All of these procedures use a single database connection.所有这些过程都使用单个数据库连接。 In every SP, I need to determine a if mysql temporary table already exists or not.在每个 SP 中,我需要确定一个 mysql 临时表是否已经存在。 if it already exists, then I'll use it's values, otherwise the SP will create & fill temporary table & other SPs (on same connection of course!) will use temporary table results.如果它已经存在,那么我将使用它的值,否则 SP 将创建并填充临时表,其他 SP(当然在同一连接上!)将使用临时表结果。

But I don't know how should I check if the temporary table already exists or not, I mean something like this:但我不知道我应该如何检查临时表是否已经存在,我的意思是这样的:

IF temporaryTablename EXISTS THEN
   ...
ELSE
   ...
END IF;

any idea?任何的想法?

It has the IF NOT EXISTS ( 13.1.17. CREATE TABLE Syntax ) option when creating a table, you can use in this case.创建表时,它具有 IF NOT EXISTS ( 13.1.17. CREATE TABLE Syntax ) 选项,您可以在这种情况下使用。

Example:例子:

DELIMITER $$

CREATE PROCEDURE `temp_sp1`()
BEGIN
    CREATE TEMPORARY TABLE IF NOT EXISTS `temp_table` (
      `col2` int(11) DEFAULT NULL,
      `col3` int(11) DEFAULT NULL
    );
    INSERT INTO `temp_table` (`col2`, `col3`) VALUES (4, 5);
    SELECT `col2`, `col3` FROM `temp_table`;
END$$

DELIMITER ;

SQL Fiddle demo SQL 小提琴演示

UPDATE更新

...
DECLARE `no_such_table` TINYINT(1) DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLSTATE VALUE '42S02' SET `no_such_table` := 1;
DO (SELECT NULL FROM `temp_table` LIMIT 0);
IF (`no_such_table`) THEN
   ...  
ELSE
   ...  
END IF;
...

For some reason wchiquito's UPDATE doesn't work for me, so I modified it into this:出于某种原因,wchiquito 的 UPDATE 对我不起作用,所以我将其修改为:

CREATE PROCEDURE check_table_existence (IN table_name CHAR(64))
BEGIN
    DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' SET @err = 1;
    SET @err = 0;
    SET @table_name = table_name;
    SET @sql_query = CONCAT('SELECT NULL 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:然后:

CALL check_table_existence('existent_table');
SELECT @table_exists;

gives

+---------------+
| @table_exists |
+---------------+
|             1 |
+---------------+

and 0 otherwise.否则为 0。

It is also a workaround, but it works fine for me.这也是一种解决方法,但对我来说效果很好。 It works for TEMPORARY TABLE as well.它也适用于临时表。

I use this:我用这个:

CREATE FUNCTION `TableExists`(tableName text) RETURNS bit(1)
    DETERMINISTIC
BEGIN
    return (SELECT count(*) FROM information_schema.tables where table_name = tableName and table_schema=schema() limit 1) > 0;
END

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

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