DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`nest_delete`(
	 vTable VARCHAR(45)
    ,vNodeId INT
)
BEGIN
	DECLARE vMyRight INT;
	DECLARE vMyLeft INT;
	DECLARE vMyWidth INT;

	DROP TEMPORARY TABLE IF EXISTS aux;
	CREATE TEMPORARY TABLE aux
		SELECT 0 rgt, 0 lft, 0 wdt;
	
	SET vTable = util.quoteIdentifier(vTable);

	EXECUTE IMMEDIATE CONCAT(
		'UPDATE aux a 
				JOIN ', vTable, ' t 
			SET a.rgt = t.rgt, 
				a.lft = t.lft,
				a.wdt = t.rgt - t.lft + 1 
			WHERE t.id = ?')
		USING vNodeId;

	SELECT rgt, lft, wdt 
		INTO vMyRight, vMyLeft, vMyWidth 
		FROM aux;

	DROP TEMPORARY TABLE aux;

	EXECUTE IMMEDIATE CONCAT(
		'DELETE FROM ', vTable, 
			' WHERE lft BETWEEN ? AND ?')
		USING vMyLeft, vMyRight;

	EXECUTE IMMEDIATE CONCAT(
		'UPDATE ', vTable, 
			' SET rgt = rgt - ? 
			WHERE rgt > ? 
			ORDER BY rgt')
		USING vMyWidth,vMyRight;

	EXECUTE IMMEDIATE CONCAT(
		'UPDATE ', vTable, 
			' SET lft = lft - ?
			WHERE lft > ? 
			ORDER BY lft')
		USING vMyWidth, vMyRight;
END$$
DELIMITER ;
