Visa ett inlägg
Oläst 2013-06-03, 23:18 #2
Conny Westh Conny Westh är inte uppkopplad
Klarade millennium-buggen
 
Reg.datum: Aug 2005
Inlägg: 5 166
Conny Westh Conny Westh är inte uppkopplad
Klarade millennium-buggen
 
Reg.datum: Aug 2005
Inlägg: 5 166
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;
Vad som återstår är att göra en Procedur som kanske heter StoreStructure() och som i sin tur anropar Splitter() och sparar resultatet i en permanent tabellstruktur.

Senast redigerad av Conny Westh den 2013-06-03 klockan 23:25
Conny Westh är inte uppkopplad   Svara med citatSvara med citat