substr_count mysql

244 views
Skip to first unread message

Eduardo Lagares

unread,
Apr 8, 2009, 10:05:17 AM4/8/09
to LISTA PHP
Boa tarde pessoal, ultimamente não tenho postado aqui no grupo, mais
hoje surgiu uma duvida interessante, bem vamos la:

No PHP, tenho a função substr_count para contar o numero de
ocorrencias de um caracter em uma string.

Agora preciso de uma função que faça isso no mysql.

Motivo: Preciso ordernar uma SELECT pelo numero de ocorrencias do
caracter "/" em uma COLUNA.


Se alguem souber de algo, desde ja agradeço.

Rodrigo Prestes

unread,
Apr 8, 2009, 10:27:18 AM4/8/09
to list...@googlegroups.com

I created a user-defined function in MySQL 5.0+ similar to PHP's substr_count(), since I could not find an equivalent native function in MySQL. (If there is one please tell me!!!)

delimiter ||
DROP FUNCTION IF EXISTS substrCount||
CREATE FUNCTION substrCount(s VARCHAR(255), ss VARCHAR(255)) RETURNS TINYINT(3) UNSIGNED LANGUAGE SQL NOT DETERMINISTIC READS SQL DATA
BEGIN
DECLARE count TINYINT(3) UNSIGNED;
DECLARE offset TINYINT(3) UNSIGNED;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s = NULL;

SET count = 0;
SET offset = 1;

REPEAT
IF NOT ISNULL(s) AND offset > 0 THEN
SET offset = LOCATE(ss, s, offset);
IF offset > 0 THEN
SET count = count + 1;
SET offset = offset + 1;
END IF;
END IF;
UNTIL ISNULL(s) OR offset = 0 END REPEAT;

RETURN count;
END;

||
delimiter ;

Use like this:

SELECT substrCount('/this/is/a/path', '/') `count`;

`count` would return 4 in this case. Can be used in such cases where you might want to find the "depth" of a path, or for many other uses.


Rodrigo Trindade Prestes
Bacharelando em Ciência da Computação - UFPel - 9º Semestre


2009/4/8 Eduardo Lagares <eduardo...@gmail.com>
Reply all
Reply to author
Forward
0 new messages