我写了一段代码:
CREATE PROCEDURE test()
BEGIN
DECLARE
ok INT default FALSE;
curs_r1 CURSOR FOR SELECT * FROM t WHERE (b > 1 and b < 3) and (c < 2);
curs_r2 CURSOR FOR SELECT * FROM t WHERE (a = 1) and (b > 2);
CONTINUE HANDLER FOR NOT FOUND SET ok = TRUE;
SET ok = False;
DROP TABLE IF EXISTS t;
CREATE TABLE IF NOT EXISTS t (
id int,
a int,
b int,
c int
);
DROP TABLE IF EXISTS res;
CREATE TABLE IF NOT EXISTS res (
id int not null unique,
score float
);
insert into t values (0,1,2,3), (1,1,3,2), (2,3,2,1);
--------------------------------------------
OPEN curs_r1;
SET score_r1 = 0.5;
REPEAT
FETCH curs_r1 INTO
id, a, b, c;
INSERT IGNORE INTO res VALUES (id, score_r1);
UNTIL ok END REPEAT;
CLOSE curs_r1;
--------------------------------------------
SET ok = FALSE;
OPEN curs_r2;
SET score_r2 = 0.25;
REPEAT
FETCH curs_r2 INTO
id, a, b, c;
INSERT IGNORE INTO res VALUES (id, score_r2);
UNTIL ok END REPEAT;
CLOSE curs_r2;
SELECT * FROM res;
END
但这会产生太多错误,例如:
错误:靠近第1行:接近&#34;程序&#34;:语法错误
错误:第5行附近:&#34; curs_r1&#34;:语法错误
错误:靠近第6行:靠近&#34; curs_r2&#34;:语法错误
错误:靠近第7行:接近&#34; CONTINUE&#34;:语法错误
错误:靠近第10行:接近&#34; SET&#34;:语法错误
错误:第27行附近:&#34; OPEN&#34;:语法错误
错误:靠近第28行:靠近&#34; SET&#34;:语法错误
错误:靠近第29行:接近&#34; REPEAT&#34;:语法错误
错误:接近第32行:接近&#34; IGNORE&#34;:语法错误
错误:靠近第33行:接近&#34; UNTIL&#34;:语法错误
错误:接近第34行:接近&#34; CLOSE&#34;:语法错误
错误:靠近第37行:靠近&#34; SET&#34;:语法错误
错误:第39行附近:&#34; OPEN&#34;:语法错误
错误:接近第40行:接近&#34; SET&#34;:语法错误
错误:靠近第41行:接近&#34; REPEAT&#34;:语法错误
错误:靠近第44行:接近&#34; IGNORE&#34;:语法错误
错误:接近第45行:接近&#34; UNTIL&#34;:语法错误
错误:靠近第46行:接近&#34; CLOSE&#34;:语法错误
错误:SQL:END
不完整
有没有人对根本原因有所了解吗?
非常感谢你。
上面的错误修复了(感谢Darwin的第一条线索),这是新的代码:
DELIMITER $$
DROP PROCEDURE IF EXISTS test;
CREATE PROCEDURE test()
BEGIN
DECLARE ok INT default FALSE;
DECLARE score_r1 FLOAT default 0.5;
DECLARE score_r2 FLOAT default 0.25;
DECLARE id, a, b, c INT;
DECLARE curs_r1 CURSOR FOR SELECT * FROM t WHERE (b > 1 and b < 3) and (c < 2);
DECLARE curs_r2 CURSOR FOR SELECT * FROM t WHERE (a = 1) and (b > 2);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET ok = TRUE;
SET ok = False;
DROP TABLE IF EXISTS t;
CREATE TABLE IF NOT EXISTS t (
id int,
a int,
b int,
c int
);
DROP TABLE IF EXISTS res;
CREATE TABLE IF NOT EXISTS res (
id int not null unique,
score float
);
insert into t values (0,1,2,3), (1,1,3,2), (2,3,2,1);
OPEN curs_r1;
OPEN curs_r2;
REPEAT
FETCH curs_r1 INTO id, a, b, c;
INSERT IGNORE INTO res VALUES (id, score_r1);
UNTIL ok END REPEAT;
CLOSE curs_r1;
SET ok = FALSE;
REPEAT
FETCH curs_r2 INTO id, a, b, c;
INSERT IGNORE INTO res VALUES (id, score_r2);
UNTIL ok END REPEAT;
CLOSE curs_r2;
SELECT * FROM res;
END;
$$
DELIMITER ;
在输出中,我希望看到两行id = 2且id = 1 但我只有一行id = 0且得分= 0.5
我在这里想念的是什么? 非常感谢你
答案 0 :(得分:2)
基本上你在每个语句上都收到错误信息。要从mysql
客户端创建过程,您必须将整个CREATE
语句括在DELIMITER
指令中,如下所示:
DELIMITER $$
CREATE PROCEDURE test()
BEGIN
... --code body goes here
END;
$$
DELIMITER ;
您的代码中确实存在许多其他错误,但这将解决第一个错误。
有关DELIMITER
的更多信息,请搜索Stack Overflow存档。