Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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.

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?

like image 520
Ehsan Khodarahmi Avatar asked Jan 20 '14 14:01

Ehsan Khodarahmi


People also ask

How can I check for the existence of a temporary table?

So, what is the proper way to check for temporary table existence? SELECT '#TempTable Exists'; This method takes into account the scoped temporary table, and gets its object_id from tempdb. If it exists, you will get a non-null value.

How do I view a temporary table in MySQL?

mysql> CREATE TEMPORARY TABLE t1 (c1 INT PRIMARY KEY) ENGINE=INNODB; Query INNODB_TEMP_TABLE_INFO to view the temporary table metadata. The TABLE_ID is a unique identifier for the temporary table. The NAME column displays the system-generated name for the temporary table, which is prefixed with “#sql”.

How will you check if a table exists in MySQL?

4.26 The table_exists() Procedure. Tests whether a given table exists as a regular table, a TEMPORARY table, or a view. The procedure returns the table type in an OUT parameter. If both a temporary and a permanent table exist with the given name, TEMPORARY is returned.

Can we return temporary table in stored procedure?

Stored procedures can reference temporary tables that are created during the current session. Within a stored procedure, you cannot create a temporary table, drop it, and then create a new temporary table with the same name.


1 Answers

It has the IF NOT EXISTS (13.1.17. CREATE TABLE Syntax) option when creating a table, you can use in this case.

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

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;
...
like image 82
wchiquito Avatar answered Oct 02 '22 17:10

wchiquito