正如您似乎知道的那样,您的要求是对大多数问题的特别低效的解决方案。但是,由于您特别要求它,并且(非常偶尔)这是解决问题的唯一方法(或者您个人有时间弄清楚如何解决它的唯一方法)。以下是您可以按照您的要求执行的操作:
创建您的 t1 表,例如:
CREATE TABLE t1(id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, C1 INT, C2 INT, C3 INT);
执行您描述的 SELECT,例如:
INSERT INTO t1 SELECT NULL,c1,c2,c3 FROM the_table;
现在这是您的 Row-By-Agonising-Row “ReeBAR” 低效率存储过程:
为您的过程准备空间并设置分隔符:
DROP PROCEDURE IF EXISTS ReeBAR;
DELIMITER ;;
写下你的程序:
CREATE PROCEDURE ReeBAR()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE varc1 INT DEFAULT 0;
DECLARE varc2 INT DEFAULT 0;
DECLARE varc3 INT DEFAULT 0;
SELECT COUNT(*) into n FROM t1;
set i=1;
WHILE i<=n DO
SELECT c1 FROM t1 WHERE id=i INTO varc1;
SELECT c2 FROM t1 WHERE id=i INTO varc2;
SELECT c3 FROM t1 WHERE id=i INTO varc3;
--queries which couldnt be made into set based queries go here---
SET i = i + 1;
END WHILE;
End;
或者,如果您的 id 列不连续,您可以使用以下光标形式。
CREATE PROCEDURE ReeBAR()
BEGIN
DECLARE cursor_ID INT;
DECLARE cursor_VAL VARCHAR;
DECLARE done INT DEFAULT FALSE;
DECLARE cursor_i CURSOR FOR SELECT c1,c2,c3 FROM t1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE varc1 INT DEFAULT 0;
DECLARE varc2 INT DEFAULT 0;
DECLARE varc3 INT DEFAULT 0;
OPEN cursor_i;
read_loop: LOOP
FETCH cursor_i INTO varc1, varc2, varc3;
IF done THEN
LEAVE read_loop;
END IF;
--queries which couldnt be made into set based queries go here---
END LOOP;
CLOSE cursor_i;
END;
不要忘记“结束”您使用的过程并重置分隔符
;;
DELIMITER ;
最后运行您的 ReBAR 程序
CALL ReeBAR();
(代码未经测试)