Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating temporary tables in MySQL Stored Procedure

The following procedure gives me an error when I invoke it using the CALL statement:

 CREATE DEFINER=`user`@`localhost` PROCEDURE `emp_performance`(id VARCHAR(10)) BEGIN DROP TEMPORARY TABLE IF EXISTS performance; CREATE TEMPORARY TABLE performance AS       SELECT time_in, time_out, day FROM attendance WHERE employee_id = id; END 

The error says "Unknown table 'performance' ".

This is my first time actually using stored procedures and I got my sources from Google. I just cant figure out what I am doing wrong.

like image 757
burntblark Avatar asked Mar 15 '11 08:03

burntblark


People also ask

Can we create temporary table in stored procedure MySQL?

Within a stored procedure, you cannot create a temporary table, drop it, and then create a new temporary table with the same name.

How do I create a temp table and insert data in MySQL?

In MySQL, the syntax of creating a temporary table is the same as the syntax of creating a normal table statement except the TEMPORARY keyword. Let us see the following statement which creates the temporary table: mysql> CREATE TEMPORARY TABLE table_name ( column_1, column_2, ..., table_constraints.

Can we use temporary table in MySQL?

Temporary tables were added in the MySQL Version 3.23. If you use an older version of MySQL than 3.23, you cannot use the temporary tables, but you can use Heap Tables. As stated earlier, temporary tables will only last as long as the session is alive.

What is a temporary table in MySQL?

In MySQL, a temporary table is a special type of table that (you guessed it) holds temporary data. These kinds of tables are usually created automatically and are typically only considered when certain types of problems arise—for example, when ALTER TABLE statements are run on vast sets of data.


1 Answers

I've tidied it up a little for you and added example code. I always keep my parameter names the same as the fields they represent but prefix with p_ which prevents issues. I do the same with variables declared in the sproc body but prefix with v_.

You can find another one of my examples here:

Generating Depth based tree from Hierarchical Data in MySQL (no CTEs)

drop procedure if exists emp_performance;  delimiter #  create procedure emp_performance ( in p_employee_id varchar(10) ) begin  declare v_counter int unsigned default 0;  create temporary table tmp engine=memory select time_in, time_out   from attendance where employee_id = p_employee_id;  -- do stuff with tmp...  select count(*) into v_counter from tmp;  -- output and cleanup  select * from tmp order by time_in;  drop temporary table if exists tmp;  end#  delimiter ;  call emp_performance('E123456789'); 
like image 131
Jon Black Avatar answered Sep 20 '22 09:09

Jon Black