mysql-recursieve-stored-function
Gesponsorde koppelingen
PHP script bestanden
De tabel:
Code (php)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
CREATE TABLE categories (
`categoryid` int(10) unsigned NOT NULL auto_increment,
`name` varchar(100) NOT NULL,
`parentid` int(10) unsigned default NULL,
PRIMARY KEY (`categoryid`),
KEY `FK_categories_1` (`parentid`),
CONSTRAINT `FK_categories_1` FOREIGN KEY (`parentid`) REFERENCES `categories` (`categoryid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`categoryid` int(10) unsigned NOT NULL auto_increment,
`name` varchar(100) NOT NULL,
`parentid` int(10) unsigned default NULL,
PRIMARY KEY (`categoryid`),
KEY `FK_categories_1` (`parentid`),
CONSTRAINT `FK_categories_1` FOREIGN KEY (`parentid`) REFERENCES `categories` (`categoryid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
De stored function:
Code (php)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
DELIMITER $$
DROP FUNCTION IF EXISTS catname $$
CREATE FUNCTION catname(arg_categoryid INT) RETURNS varchar(100) CHARSET utf8
BEGIN
DECLARE currentCategoryId INT;
DECLARE categoryname VARCHAR(100);
DECLARE padder VARCHAR(20) DEFAULT '';
SET currentCategoryId = arg_categoryid;
SELECT name INTO categoryname FROM categories WHERE categoryid = arg_categoryid;
catloop : LOOP
SELECT parentid INTO currentCategoryid FROM categories WHERE categoryid = currentCategoryId;
IF currentCategoryId IS NULL THEN LEAVE catloop; END IF;
SET padder = CONCAT(padder,'-');
END LOOP catloop;
RETURN CONCAT(padder,' ',categoryname);
END $$
DELIMITER ;
DROP FUNCTION IF EXISTS catname $$
CREATE FUNCTION catname(arg_categoryid INT) RETURNS varchar(100) CHARSET utf8
BEGIN
DECLARE currentCategoryId INT;
DECLARE categoryname VARCHAR(100);
DECLARE padder VARCHAR(20) DEFAULT '';
SET currentCategoryId = arg_categoryid;
SELECT name INTO categoryname FROM categories WHERE categoryid = arg_categoryid;
catloop : LOOP
SELECT parentid INTO currentCategoryid FROM categories WHERE categoryid = currentCategoryId;
IF currentCategoryId IS NULL THEN LEAVE catloop; END IF;
SET padder = CONCAT(padder,'-');
END LOOP catloop;
RETURN CONCAT(padder,' ',categoryname);
END $$
DELIMITER ;
Voorbeeld data