日期:2014-05-16 浏览次数:21005 次
mysql> desc tree_test; +———–+————-+——+—–+———+—————-+ | Field | Type | Null | Key | Default | Extra | +———–+————-+——+—–+———+—————-+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(11) | NO | | | | | parent_id | int(11) | NO | | NULL | | +———–+————-+——+—–+———+—————-+ 3 rows in set (0.00 sec)
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc1`(IN top int) BEGIN DROP VIEW IF EXISTS tree_test_view; SET @sqlstr = "CREATE VIEW tree_test_view as "; SET @sqlstr = CONCAT(@sqlstr , "SELECT id FROM tree_test WHERE parent_id = 0 LIMIT ", top); PREPARE stmt FROM @sqlstr; EXECUTE stmt; DEALLOCATE PREPARE stmt; END
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc2`() BEGIN DECLARE done INT DEFAULT 0; DECLARE temp_id INT; DECLARE cur CURSOR for( SELECT id from tree_test_view); DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur; FETCH cur INTO temp_id; WHILE done <> 1 DO delete tree_test WHERE id = temp_id or parent_id = temp_id; FETCH cur INTO temp_id; END WHILE; CLOSE cur; END
REATE DEFINER=`root`@`localhost` PROCEDURE `tree_test_query`(IN top int) BEGIN call proc1(top); call proc2(); END
CREATE DEFINER=`root`@`localhost` PROCEDURE `tree_test_query`(IN top int) BEGIN DECLARE done INT DEFAULT 0; DECLARE temp_id INT; DECLARE cur CURSOR for( SELECT id from tree_test_view); DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; DROP VIEW IF EXISTS tree_test_view; SET @sqlstr = "CREATE VIEW tree_test_view as "; SET @sqlstr = CONCAT(@sqlstr , "SELECT id FROM tree_test WHERE parent_id = 0 LIMIT ", top); PREPARE stmt FROM @sqlstr; EXECUTE stmt; DEALLOCATE PREPARE stmt; OPEN cur; FETCH cur INTO temp_id; WHILE done <> 1 DO