begin
DECLARE i INT DEFAULT 4700;
DECLARE y INT;
DECLARE e, w, s, n INT;
WHILE i > 0 DO
SELECT `east`, `west`, `south`, `north` INTO e, w, s, n FROM `cpl_city` WHERE `id` = i;
SELECT `id` INTO `y` FROM `cpl_city` WHERE `east` >= e AND `west` <= w AND `north` >= n AND `south` <= s ORDER BY `south`, `west`, `population` LIMIT 1;
IF (y <> i) THEN
UPDATE `cpl_city` SET `parent_id` = y WHERE `id` = i;
END IF;
SET i = i - 1;
SET e = w = n = s = NULL;
END WHILE;
END
DROP PROCEDURE IF EXISTS t1;
DELIMITER //
CREATE PROCEDURE t1 ()
BEGIN
DECLARE e, w, s, n INT;
SELECT 1 INTO e;
SELECT 2 INTO w;
SELECT 3 INTO s;
SELECT 4 INTO n;
SET e = w = s = n = NULL;
SELECT e,w,s,n;
END//
DELIMITER ;
DROP PROCEDURE IF EXISTS t2;
DELIMITER //
CREATE PROCEDURE t2 ()
BEGIN
DECLARE e, w, s, n INT;
SELECT 1 INTO e;
SELECT 2 INTO w;
SELECT 3 INTO s;
SELECT 4 INTO n;
SET e = NULL;
SET w = NULL;
SET s = NULL;
SET n = NULL;
SELECT e,w,s,n;
END//
DELIMITER ;
CALL t1();
CALL t2();
+------+------+------+------+
| e | w | s | n |
+------+------+------+------+
| NULL | 2 | 3 | 4 |
+------+------+------+------+
+------+------+------+------+
| e | w | s | n |
+------+------+------+------+
| NULL | NULL | NULL | NULL |
+------+------+------+------+