curosr与查询完全一致:SELECT Crc32 FROM tableName。我想读取Crc32列中的所有行,并根据前四个字符找到一个与四位数同名的表
错误:
0 12:58:57 call ShowNewUserComments("User66") Error Code: 1146. Table 'comments.tableName' doesn't exist
通话程序:
call ShowNewUserComments("User66");
代码
DELIMITER $$
DROP PROCEDURE IF EXiSTS ShowNewUserComments $$
CREATE PROCEDURE `ShowNewUserComments`(tableName varchar(255)/*, Date TIMESTAMP*/)
BEGIN
DECLARE recordNotFound INTEGER DEFAULT 0;
DECLARE oneRow VARCHAR(10) DEFAULT "";
DECLARE getCrc32,i int (11);
DECLARE myCursor CURSOR FOR SELECT Crc32 FROM tableName;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET recordNotFound = 1;
OPEN myCursor;
set i = 0;
allRows: LOOP
FETCH myCursor INTO oneRow;
set i = i + 1;
IF recordNotFound THEN
LEAVE allRows;
END IF;
END LOOP allRows;
CLOSE myCursor;
END
答案 0 :(得分:0)
您无法直接将变量中的表名替换为MySQL中的查询,因为您需要使用PREPARE
这样的动态sql:
DELIMITER $$
DROP PROCEDURE IF EXiSTS ShowNewUserComments $$
CREATE PROCEDURE `ShowNewUserComments`(tableName varchar(255)/*, Date TIMESTAMP*/)
BEGIN
DECLARE recordNotFound INTEGER DEFAULT 0;
DECLARE oneRow VARCHAR(10) DEFAULT "";
DECLARE getCrc32,i int (11);
DECLARE myCursor CURSOR FOR SELECT Crc32 FROM temp_table;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET recordNotFound = 1;
DROP TEMPORARY TABLE IF EXISTS temp_table;
SET @query1 = CONCAT('CREATE TEMPORARY TABLE temp_table AS
SELECT Crc32
FROM ',tableName,' ');
PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;
OPEN myCursor;
set i = 0;
allRows: LOOP
FETCH myCursor INTO oneRow;
set i = i + 1;
IF recordNotFound THEN
LEAVE allRows;
END IF;
END LOOP allRows;
CLOSE myCursor;
DROP TEMPORARY TABLE IF EXISTS temp_table;
END