我在MySQL 5.5中遇到了存储过程的问题。这是程序必须运行的表:
Table `diba`:
----------------------------------------------------
Column | Type | Null | Default | Links to
----------------------------------------------------
ParentID | int(11) | No | | articoli -> id
ChildID | int(11) | No | | articoli -> id
Quantity | int(11) | No |
lvl | int(11) | No | 0
这是程序本身:
DELIMITER //
CREATE PROCEDURE RenumberLevels()
DETERMINISTIC
BEGIN
DECLARE lvl_counter INT;
SET lvl_counter = 1;
UPDATE `diba` SET `diba`.`lvl` = CASE WHEN `diba`.`ParentID` IS NULL THEN 1 ELSE 0 END;
WHILE EXISTS (SELECT * FROM `diba` WHERE `diba`.`lvl` = 0) DO
UPDATE `diba` SET `diba`.`lvl` = lvl_counter +1 WHERE (SELECT `D2`.`lvl` FROM `diba` AS D2
WHERE D2.ChildID = `diba`.`ParentID`) > 0 AND `diba`.`lvl` = 0;
SET `diba`.`lvl` = lvl_counter + 1;
END WHILE;
END//
DELIMITER ;
产生的错误是:
#1193 - Unknown system variable 'lvl'
这个程序有什么问题?
答案 0 :(得分:3)
这是创建过程语句的正确版本:
DELIMITER $$
CREATE PROCEDURE `RenumberLevels`()
DETERMINISTIC
BEGIN
DECLARE lvl_counter INT;
SET lvl_counter = 1;
UPDATE `diba` SET `diba`.`lvl` = CASE WHEN `diba`.`ParentID` IS NULL THEN 1 ELSE 0 END;
WHILE EXISTS (SELECT * FROM diba WHERE lvl = 0) DO
CREATE TABLE dibatemp AS
SELECT D2.lvl FROM diba AS D2 LEFT JOIN diba ON diba.ParentID=D2.ChildID;
UPDATE diba
SET lvl = lvl_counter +1 WHERE lvl IN (SELECT lvl FROM dibatemp) > 0 AND lvl = 0;
DROP TABLE dibatemp;
SET lvl_counter = lvl_counter + 1;
END WHILE;
END$$
DELIMITER ;
答案 1 :(得分:1)
在说
的行上SET `diba`.`lvl` = lvl_counter + 1;
我认为你的意思是
SET lvl_counter = lvl_counter + 1;