| FAQ |
| Kalender |
|
|
#2 | ||
|
|||
|
Klarade millennium-buggen
|
Jag har inte en komplett lösning men lite procedurer och funktioner på vägen...
Kod:
delimiter $$
CREATE DEFINER=`root`@`localhost` FUNCTION `substrCount`(s VARCHAR(255), ss VARCHAR(255)) RETURNS tinyint(3) unsigned
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$$
Kod:
delimiter $$ CREATE DEFINER=`root`@`localhost` FUNCTION `stringSplit`( x VARCHAR(255), delim VARCHAR(12), pos INT) RETURNS varchar(255) CHARSET latin1 RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos), LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1), delim, '')$$ Kod:
delimiter $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `splitter`(x varchar(255), delim varchar(12)) BEGIN SET @Valcount = substrCount(x,delim)+1; SET @v1=0; SET @v2=0; drop temporary table if exists _splitResults; create temporary table _splitResults ( id int unsigned NOT NULL PRIMARY KEY, parent_id int default null, split_value varchar(255) not null ) ENGINE=Memory; WHILE (@v1 < @Valcount) DO set @val = stringSplit(x,delim,@v1+1); IF @v1 >0 THEN BEGIN SET @v2 = @v2 +1; INSERT INTO _splitResults (id, parent_id,split_value) VALUES (@v1+1, @v2,@val); END; ELSE BEGIN INSERT INTO _splitResults (id, parent_id,split_value) VALUES (@v1+1, NULL,@val); END; end if; SET @v1 = @v1 + 1; END WHILE; select * from _splitResults; END$$ Slutligen lite testkod hur man använder dessa.... Kod:
delimiter ;
use wn;
-- http://www.montrealseocompany.com/2012/04/17/mysql-split-string-into-rows-function/
call splitter('mange/gurra/hanna/olle/greta/sven/lena/nisse','/');
-- select * from _splitresults;
select * from _splitresults;
drop table _splitresults;
Senast redigerad av Conny Westh den 2013-06-04 klockan 00:25 |
||
|
|
Svara med citat
|
| Ämnesverktyg | |
| Visningsalternativ | |
|
|