开发者

mySQL Stored Procedure for splitting strings by delimiter

I'm into writing a stored procedure which explodes a passed string by a passed delimiter and returns the n-th element of the result. n is passed too.

So this is what I came up with:

CREATE PROCEDURE SPLIT(IN strToSplit text, IN strDelimiter varchar(1), IN nPartToGet int,OUT strSlice varchar(255))
BEGIN

  SET strSlice = replace(substring(substring_index(strToSplit, str开发者_运维知识库Delimiter, nPartToGet),
    length(substring_index(strToSplit,strDelimiter, nPartToGet - 1)) + 1), strDelimiter, '')

END
;

Sadly mysql keeps naging me that I've got an syntax error in there. IMHO this should work. Could anyone pls poke me on where I'm going wrong?

thanks in advance

  K


You need to end your SET with a ';' and, given that the client interprets ; as the delimiter, you need to change the delimiter so you can enter an actual ; into the procedure.

mysql> delimiter //
mysql> CREATE PROCEDURE SPLIT(IN strToSplit text, IN strDelimiter varchar(1), IN nPartToGet int,OUT strSlice varchar(255))
    -> BEGIN
    -> SET strSlice = replace(substring(substring_index(strToSplit, strDelimiter,
    -> nPartToGet),     length(substring_index(strToSplit,strDelimiter, 
    -> nPartToGet - 1)) + 1), strDelimiter, '');
    -> END
    -> //
Query OK, 0 rows affected (0.01 sec)
mysql> delimiter ;
mysql> CALL SPLIT('1;2;3;4;5',';',3,@str);
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @str;
+------+
| @str |
+------+
| 3    |
+------+
1 row in set (0.00 sec)

Relevant docs: http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜