CREATE TABLE IF NOT EXISTS students (
	id int auto_increment,
    name varchar(255) not null,
	age int,
	primary key(id)
);

DROP FUNCTION IF EXISTS f_temp_table_sample;
CREATE FUNCTION f_temp_table_sample(pv_nID INTEGER)
 RETURNS VARCHAR(255)
BEGIN
	DECLARE lv_cError VARCHAR(255) DEFAULT ''; 
	DECLARE lv_nId, lv_nAge, lv_nRet INT; 
	DECLARE lv_cName VARCHAR(255) DEFAULT ''; 
	
	DECLARE students_rows CURSOR FOR 
		SELECT 
			stds.id,
			stds.name,
			stds.age
        FROM students stds
        LEFT OUTER JOIN students_tmp stds_tmp ON stds_tmp.id=stds.id
		WHERE 
		stds.id=pv_nID; 

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET lv_cError='-2'; 

	CREATE OR REPLACE TEMPORARY TABLE students_tmp 
		ENGINE=MEMORY
		SELECT 
			students.id
		FROM 
			students 
		WHERE 
			students.id=-1; 
	
	IF NOT EXISTS (SELECT * FROM students_tmp) THEN
		INSERT INTO students_tmp
		SELECT 
			students.id
		FROM 
			students 
		WHERE 
			students.id=pv_nID; 
	END IF; 

	SET lv_cError=''; 
	
	OPEN students_rows; 
	REPEAT 
		FETCH students_rows INTO lv_nId, lv_nAge, lv_cName; 
		IF lv_cError='' THEN
			SELECT 1 INTO lv_nRet; 
		END IF; 
	UNTIL lv_cError<>'' END REPEAT; 
	CLOSE students_rows; 
	DROP TEMPORARY TABLE IF EXISTS students_tmp; 

	RETURN lv_cError; 
END;


SELECT f_temp_table_sample(1);
SELECT f_temp_table_sample(2);
