在老外的站点上看到非常不错的 Explode 存储过程实现。为了能方便处理 SELECT 出来的结果集字段(select lib_Explode(‘,’,string) from xxx; ),我改了一个 FUNCTION ,基本上是一样的。但需要将里面建表的语句单独拿出来。
EXPLODE 方法:
view sourceprint?
01.DROP TABLE IF EXISTS lib_Explode;
02.CREATE TABLE lib_Explode(
03.`pos` int unsigned NOT NULL auto_increment,
04.`val` VARCHAR(255) NOT NULL,
05.PRIMARY KEY (`pos`)
06.) ENGINE=Memory COMMENT='Explode() results.';
07.
08.
09.CREATE FUNCTION lib_Explode( sSepar VARCHAR(255), saVal TEXT ) returns INTEGER
10.body:
11.BEGIN
12.IF sSepar IS NULL OR saVal IS NULL THEN LEAVE body; END IF;
13.
14.SET @saTail = saVal;
15.SET @iSeparLen = LENGTH( sSepar );
16.SET @total = 0;
17.
18.create_layers:
19.WHILE @saTail != '' DO
20.
21.# Get the next value
22.SET @sHead = SUBSTRING_INDEX(@saTail, sSepar, 1);
23.SET @saTail = SUBSTRING( @saTail, LENGTH(@sHead) + 1 + @iSeparLen );
24.INSERT INTO lib_Explode SET val = @sHead;
25.
26.END WHILE;
27.
28.SELECT count(*) INTO @total from lib_Explode;
29.return @total;
30.
31.END; //
32.EXPLODE 存储过程:
33.
34.CREATE PROCEDURE lib_Explode( sSepar VARCHAR(255), saVal TEXT )
35.body:
36.BEGIN
37.
38.DROP TEMPORARY TABLE IF EXISTS lib_Explode;
39.CREATE TEMPORARY TABLE lib_Explode(
40.`pos` int unsigned NOT NULL auto_increment,
41.`val` VARCHAR(255) NOT NULL,
42.PRIMARY KEY (`pos`)
43.) ENGINE=Memory COMMENT='Explode() results.';
44.
45.IF sSepar IS NULL OR saVal IS NULL THEN LEAVE body; END IF;
46.
47.SET @saTail = saVal;
48.SET @iSeparLen = LENGTH( sSepar );
49.
50.create_layers:
51.WHILE @saTail != '' DO
52.
53.# Get the next value
54.SET @sHead = SUBSTRING_INDEX(@saTail, sSepar, 1);
55.SET @saTail = SUBSTRING( @saTail, LENGTH(@sHead) + 1 + @iSeparLen );
56.INSERT INTO lib_Explode SET val = @sHead;
57.
58.END WHILE;
59.
60.END; //
--转自