DELIMITER $$
DROP PROCEDURE IF EXISTS logger $$
CREATE PROCEDURE logger(IN errorz VARCHAR(50),IN table_name VARCHAR(50))
BEGIN
DECLARE t_name VARCHAR(50);
DECLARE link_id_var INT;
DECLARE error_type_var VARCHAR(30);
DECLARE source_url_var VARCHAR(500);
DECLARE done INT DEFAULT 0;
DECLARE curl CURSOR FOR SELECT link_id, anchor_match, anchor_match FROM cursor_temp;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
DROP TEMPORARY TABLE IF EXISTS cursor_temp;
SET @query1 = CONCAT('
CREATE TEMPORARY TABLE cursor_temp AS
SELECT p.link_id, anchor_match, source_url
FROM ',table_name,' AS p
INNER JOIN link_results AS l
ON p.page_r_id = l.page_r_id
INNER JOIN links AS ls
ON ls.link_id = p.link_id
WHERE anchor_match="None"
');
PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;
OPEN curl;
my_loop:LOOP
FETCH curl INTO link_id_var,error_type_var,source_url_var;
INSERT INTO errors (link_id,error_type,source_url) VALUES (link_id_var,errorz,source_url_var) ON DUPLICATE KEY UPDATE error_type=errorz,source_url=source_url_var;
IF done=1 THEN
LEAVE my_loop;
END IF;
END LOOP my_loop;
CLOSE curl;
DROP TEMPORARY TABLE IF EXISTS cursor_temp;
END$$
When I execute the statement:
call logger('anchor','page_results');
I get the source url field in my other table as being ‘None’. why?
This is because all
DECLAREstatements have to be at the top of stored procedure.You need to move this
SET @t_name=table_name;statement after allDECLAREstatements.See Manual.
EDIT: You can’t access the variables table name in cursor. Alternatively you can use dynamic sql and store the result in temporary table and use that table in cursor selection.