简体   繁体   English

在MySQL存储过程中创建临时表

[英]Creating temporary tables in MySQL Stored Procedure

The following procedure gives me an error when I invoke it using the CALL statement: 当我使用CALL语句调用它时,以下过程给出了一个错误:


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. 我只是想弄清楚我做错了什么。

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. 我始终保持我的参数名称与它们所代表的字段相同,但前缀为p_,这可以防止出现问题。 I do the same with variables declared in the sproc body but prefix with v_. 我对sproc体中声明的变量执行相同的操作,但前缀为v_。

You can find another one of my examples here: 你可以在这里找到我的另一个例子:

Generating Depth based tree from Hierarchical Data in MySQL (no CTEs) 从MySQL中的分层数据生成基于深度的树(无CTE)

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');

By default MySQL config variable sql_notes is set to 1. 默认情况下,MySQL配置变量sql_notes设置为1。

That means that DROP TEMPORARY TABLE IF EXISTS performance; 这意味着DROP TEMPORARY TABLE IF EXISTS performance; increments warning_count by one and you get a warning when a stored procedure finishes. warning_count递增1,并在存储过程完成时收到警告。

You can set sql_notes variable to 0 in my.cnf or rewrite stored procedure like that: 您可以在my.cnf中将sql_notes变量设置为0或重写存储过程,如下所示:

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

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

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